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

The following examples show how to use reactor.core.publisher.Flux#fromStream() . 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
Source File: ReactiveAdapterDefault.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@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
Source File: OrderServiceV1.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 6 votes vote down vote up
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
Source File: R011_LetsMeetFlux.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@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 4
Source File: R021_FluxSubscribing.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@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 5
Source File: R021_FluxSubscribing.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
@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 6
Source File: TestController.java    From SpringAll with 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 7
Source File: FluxCreationTests.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: ExampleTests.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 5 votes vote down vote up
@Test
public void data4() {
	// tag::4[]
	Stream<String> items = Arrays.asList("alpha", "bravo", "charlie").stream();
	Flux.fromStream(items);
	// end::4[]
}
 
Example 9
Source File: StepVerifierTests.java    From reactor-core with 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 10
Source File: R022_HowToCreateMonoAndFlux.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void creatingEagerFluxFromStreamIncorrectly2() throws Exception {
	//when
	Flux.fromStream(Stream.of(killHumanity(), destroyEarth()));

	//then
	assertThat(killed).isTrue();
	assertThat(destroyed).isTrue();
}
 
Example 11
Source File: R022_HowToCreateMonoAndFlux.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void creatingLazyFluxFromStreamCorrectly() throws Exception {
	//when
	Flux.fromStream(() -> Stream.of(killHumanity(), destroyEarth()));

	//then
	assertThat(killed).isFalse();
	assertThat(destroyed).isFalse();
}
 
Example 12
Source File: InMemoryLoadBalancerStore.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<LoadBalancerTargetState> getLoadBalancerTargets(String loadBalancerId) {
    return Flux.fromStream(
            targets.entrySet().stream()
                    .filter(entry -> entry.getKey().getLoadBalancerId().equals(loadBalancerId))
                    .map(LoadBalancerTargetState::from)
    );
}
 
Example 13
Source File: ShoppingCartServiceV1.java    From spring-cloud-event-sourcing-example with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 14
Source File: R011_LetsMeetFlux.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
@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 15
Source File: Iterators.java    From james-project with 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 16
Source File: CassandraMailQueueBrowser.java    From james-project with Apache License 2.0 4 votes vote down vote up
private Flux<Slice> allSlicesStartingAt(Instant browseStart) {
    return Flux.fromStream(Slice.of(browseStart).allSlicesTill(clock.instant(), configuration.getSliceWindow()));
}
 
Example 17
Source File: DataHandler.java    From Spring-5.0-Cookbook with 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 18
Source File: DataHandler.java    From Spring-5.0-Cookbook with 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
Source File: ReactorInvokerImpl.java    From cxf with 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 20
Source File: ReactorCustomSubscriber.java    From Spring-5.0-Projects with MIT License 3 votes vote down vote up
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);
	}