Java Code Examples for reactor.core.publisher.Flux#fromStream()

The following examples show how to use reactor.core.publisher.Flux#fromStream() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public <T> Flux<T> toFlux(@Nullable Object source) {
    if (source instanceof Flux) {
        return (Flux) source;
    } else if (source instanceof Iterable) {
        return Flux.fromIterable((Iterable) source);
    } else if (source instanceof Stream) {
        return Flux.fromStream((Stream) source);
    } else if (source instanceof Publisher) {
        return Flux.from((Publisher) source);
    } else if (source == null) {
        return Flux.empty();
    } else if (source.getClass().isArray()) {
        return Flux.fromArray((T[]) source);
    }
    return (Flux<T>) Flux.just(source);
}
 
Example 2
public Order getOrder(String orderId, Boolean validate) {
    // Get the order for the event
    Order order = orderRepository.findOne(orderId);

    if (validate) {
        try {
            // Validate the account number of the event's order belongs to the user
            validateAccountNumber(order.getAccountNumber());
        } catch (Exception ex) {
            return null;
        }
    }

    Flux<OrderEvent> orderEvents =
            Flux.fromStream(orderEventRepository.findOrderEventsByOrderId(order.getOrderId()));

    // Aggregate the state of order
    return orderEvents
            .takeWhile(orderEvent -> orderEvent.getType() != OrderEventType.DELIVERED)
            .reduceWith(() -> order, Order::incorporate)
            .get();
}
 
Example 3
@Test
public void noWorkHappensWithoutSubscription() throws Exception {
	//given
	AtomicBoolean flag = new AtomicBoolean();

	//when
	log.info("About to create Flux");
	Flux.fromStream(() -> {
		log.info("Doing hard work");
		flag.set(true);
		return Stream.of(1, 2, 3);
	});

	//then
	assertThat(flag).isFalse();
}
 
Example 4
@Test
public void subscriptionOfManyNotifications() throws Exception {
	//given
	AtomicBoolean flag = new AtomicBoolean();
	log.info("About to create Flux");

	//when
	final Flux<Integer> work = Flux.fromStream(() -> {
		log.info("Doing hard work");
		flag.set(true);
		return Stream.of(1, 2, 3);
	});

	//then
	log.info("Flux was created");

	work.subscribe(
			i -> log.info("Received {}", i),
			ex -> log.error("Opps!", ex),
			() -> log.info("Flux completed")
	);

	log.info("Work is done");
}
 
Example 5
@Test
public void fluxComputesManyTimes() throws Exception {
	//given
	AtomicInteger c = new AtomicInteger();
	final Flux<Integer> flux = Flux.fromStream(() ->
			Stream.of(c.incrementAndGet(), c.incrementAndGet()));

	//when
	final List<Integer> first = flux.collectList().block();
	final List<Integer> second = flux.collectList().block();

	//then
	assertThat(c).hasValue(4);
	assertThat(first).containsExactly(1, 2);
	assertThat(second).containsExactly(3, 4);
}
 
Example 6
@Test
public void createAFlux_fromStream() {
  Stream<String> fruitStream = 
       Stream.of("Apple", "Orange", "Grape", "Banana", "Strawberry");
   
  Flux<String> fruitFlux = Flux.fromStream(fruitStream);
   
  StepVerifier.create(fruitFlux)
      .expectNext("Apple")
      .expectNext("Orange")
      .expectNext("Grape")
      .expectNext("Banana")
      .expectNext("Strawberry")
      .verifyComplete();
}
 
Example 7
@Test
public void data4() {
	// tag::4[]
	Stream<String> items = Arrays.asList("alpha", "bravo", "charlie").stream();
	Flux.fromStream(items);
	// end::4[]
}
 
Example 8
Source Project: reactor-core   File: StepVerifierTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void verifyRecordWith2() {
	final List<Integer> source = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

	Flux<Integer> flux = Flux.fromStream(source.stream());

	StepVerifier.create(flux)
	            .recordWith(ArrayList::new)
	            .expectNextCount(10)
	            .consumeRecordedWith(c -> assertThat(c).containsExactlyElementsOf(source))
	            .expectComplete()
	            .verify();
}
 
Example 9
@Test
public void creatingEagerFluxFromStreamIncorrectly2() throws Exception {
	//when
	Flux.fromStream(Stream.of(killHumanity(), destroyEarth()));

	//then
	assertThat(killed).isTrue();
	assertThat(destroyed).isTrue();
}
 
Example 10
@Test
public void creatingLazyFluxFromStreamCorrectly() throws Exception {
	//when
	Flux.fromStream(() -> Stream.of(killHumanity(), destroyEarth()));

	//then
	assertThat(killed).isFalse();
	assertThat(destroyed).isFalse();
}
 
Example 11
@Override
public Flux<LoadBalancerTargetState> getLoadBalancerTargets(String loadBalancerId) {
    return Flux.fromStream(
            targets.entrySet().stream()
                    .filter(entry -> entry.getKey().getLoadBalancerId().equals(loadBalancerId))
                    .map(LoadBalancerTargetState::from)
    );
}
 
Example 12
/**
 * Aggregate the cart events of a user and return a {@link ShoppingCart} object
 *
 * @param user    is the user to retrieve the shopping cart for
 * @param catalog is the catalog used to generate the shopping cart
 * @return a shopping cart representing the aggregate state of the user's cart
 * @throws Exception
 */
public ShoppingCart aggregateCartEvents(User user, Catalog catalog) throws Exception {
    Flux<CartEvent> cartEvents =
            Flux.fromStream(cartEventRepository.getCartEventStreamByUser(user.getId()));

    // Aggregate the state of the shopping cart
    ShoppingCart shoppingCart = cartEvents
            .takeWhile(cartEvent -> !ShoppingCart.isTerminal(cartEvent.getCartEventType()))
            .reduceWith(() -> new ShoppingCart(catalog), ShoppingCart::incorporate)
            .get();

    shoppingCart.getLineItems();

    return shoppingCart;
}
 
Example 13
@Test
public void fluxIsLazy() throws Exception {
	//given
	AtomicInteger c = new AtomicInteger();

	//when
	Flux.fromStream(() -> Stream.of(c.incrementAndGet(), c.incrementAndGet()));

	//then
	assertThat(c.get()).isZero();
}
 
Example 14
Source Project: SpringAll   File: TestController.java    License: MIT License 5 votes vote down vote up
@GetMapping(value = "async/flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> asyncFlux() {
    logger.info("async method start");
    Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "int value:" + i;
    }));
    logger.info("async method end");
    return result;
}
 
Example 15
Source Project: Spring-5.0-Cookbook   File: DataHandler.java    License: MIT License 4 votes vote down vote up
public Mono<ServerResponse> stream(ServerRequest req) {
	Stream<String> streamData = Stream.of("i", "love", "reactive", "programming").sorted()
			.map((str) -> str.toUpperCase() + " ");
	Flux<String> flux = Flux.fromStream(streamData);
	return ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(flux, String.class);
}
 
Example 16
Source Project: cxf   File: ReactorInvokerImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T> Flux<T> flux(String name, Class<T> responseType) {
    Future<Response> futureResponse = webClient.async().method(name);
    return Flux.fromStream(() -> 
        StreamSupport.stream(toIterable(futureResponse, responseType).spliterator(), false));
}
 
Example 17
Source Project: james-project   File: Iterators.java    License: Apache License 2.0 4 votes vote down vote up
public static <T> Flux<T> toFlux(Iterator<T> iterator) {
    return Flux.fromStream(toStream(iterator));
}
 
Example 18
Source Project: Spring-5.0-Cookbook   File: DataHandler.java    License: MIT License 4 votes vote down vote up
public Mono<ServerResponse> stream(ServerRequest req) {
	Stream<String> streamData = Stream.of("i", "love", "reactive", "programming").sorted()
			.map((str) -> str.toUpperCase() + " ");
	Flux<String> flux = Flux.fromStream(streamData);
	return ok().contentType(MediaType.APPLICATION_STREAM_JSON).body(flux, String.class);
}
 
Example 19
private Flux<Slice> allSlicesStartingAt(Instant browseStart) {
    return Flux.fromStream(Slice.of(browseStart).allSlicesTill(clock.instant(), configuration.getSliceWindow()));
}
 
Example 20
public static void main(String[] args) {

		Flux<String> hrUsers = Flux.fromStream(Stream.of(
				"John", "Komal", "Harmi", "Bhakti", "Tom","Peter"));
		
		CustomSubscriber cs = new CustomSubscriber();
		
		hrUsers.subscribe(cs);
	}