Java Examples for reactor.core.publisher.Flux

The following java examples will help you to understand the usage of reactor.core.publisher.Flux. These source code samples are taken from different open source projects.

Example 1
Project: camelinaction2-master  File: CamelNumbersTest.java View source code
@Test
public void testNumbers() throws Exception {
    CamelReactiveStreamsService reactive = CamelReactiveStreams.get(context);
    // create a published that receive from the numbers stream
    Publisher<Integer> numbers = reactive.fromStream("numbers", Integer.class);
    // use stream engine to subscribe from the publisher
    // where we filter out the big numbers which is logged
    Flux.from(numbers).filter( n -> n > 5).doOnNext( c -> log.info("Streaming big number {}", c)).subscribe();
    // let it run for 10 seconds
    Thread.sleep(10000);
}
Example 2
Project: webflux-streaming-showcase-master  File: QuoteGenerator.java View source code
public Flux<Quote> fetchQuoteStream(Duration period) {
    return Flux.generate(() -> 0, (BiFunction<Integer, SynchronousSink<Quote>, Integer>) ( index,  sink) -> {
        Quote updatedQuote = updateQuote(prices.get(index));
        sink.next(updatedQuote);
        return ++index % prices.size();
    }).zipWith(Flux.interval(period)).map( t -> t.getT1()).map( quote -> {
        quote.setInstant(Instant.now());
        return quote;
    }).share().log();
}
Example 3
Project: reactor-master  File: EventStreamCodec.java View source code
static Flux<ServerSentEvent> decode(HttpClientResponse response) {
    return response.addHandler(createDecoder()).receive().asString().windowWhile( s -> !s.isEmpty(), // TODO: Remove Prefetch with reactor-core 3.0.6
    Integer.MAX_VALUE).concatMap( window -> window.reduce(ServerSentEvent.builder(), EventStreamCodec::parseLine)).map(ServerSentEvent.Builder::build).filter( sse -> sse.getData() != null || sse.getEventType() != null || sse.getId() != null || sse.getRetry() != null);
}
Example 4
Project: reactor-core-master  File: FluxWithProcessorVerification.java View source code
@Override
public Processor<Integer, Integer> createProcessor(int bufferSize) {
    Flux<String> otherStream = Flux.just("test", "test2", "test3");
    System.out.println("Providing new downstream");
    FluxProcessor<Integer, Integer> p = WorkQueueProcessor.create("fluxion-raw-fork", bufferSize);
    cumulated.set(0);
    cumulatedJoin.set(0);
    BiFunction<Integer, String, Integer> combinator = ( t1,  t2) -> t1;
    return FluxProcessor.wrap(p, p.groupBy( k -> k % 2 == 0).flatMap( stream -> stream.scan(( prev,  next) -> next).map( integer -> -integer).filter( integer -> integer <= 0).map( integer -> -integer).bufferTimeout(batch, Duration.ofMillis(50)).flatMap(Flux::fromIterable).doOnNext( array -> cumulated.getAndIncrement()).flatMap( i -> Flux.zip(Flux.just(i), otherStream, combinator)).doOnNext(this::monitorThreadUse)).doOnNext( array -> cumulatedJoin.getAndIncrement()).subscribeWith(TopicProcessor.create("fluxion-raw-join", bufferSize)).doOnError(Throwable::printStackTrace).awaitOnSubscribe());
}
Example 5
Project: spring-reactive-master  File: StringEncoder.java View source code
@Override
public Flux<DataBuffer> encode(Publisher<? extends String> inputStream, DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Object... hints) {
    Charset charset;
    if (mimeType != null && mimeType.getCharset() != null) {
        charset = mimeType.getCharset();
    } else {
        charset = DEFAULT_CHARSET;
    }
    return Flux.from(inputStream).map( s -> {
        byte[] bytes = s.getBytes(charset);
        DataBuffer dataBuffer = bufferFactory.allocateBuffer(bytes.length);
        dataBuffer.write(bytes);
        return dataBuffer;
    });
}
Example 6
Project: spring-cloud-stream-master  File: MessageChannelToObservableSenderParameterAdapter.java View source code
@Override
public ObservableSender adapt(MessageChannel bindingTarget, MethodParameter parameter) {
    return new ObservableSender() {

        private FluxSender fluxSender = MessageChannelToObservableSenderParameterAdapter.this.messageChannelToFluxSenderArgumentAdapter.adapt(bindingTarget, parameter);

        @Override
        public Single<Void> send(Observable<?> observable) {
            Publisher<?> adaptedPublisher = RxReactiveStreams.toPublisher(observable);
            return RxReactiveStreams.toSingle(this.fluxSender.send(Flux.from(adaptedPublisher)));
        }
    };
}
Example 7
Project: spring-framework-master  File: DataBufferDecoderTests.java View source code
@Test
public void decode() {
    DataBuffer fooBuffer = stringBuffer("foo");
    DataBuffer barBuffer = stringBuffer("bar");
    Flux<DataBuffer> source = Flux.just(fooBuffer, barBuffer);
    Flux<DataBuffer> output = this.decoder.decode(source, ResolvableType.forClassWithGenerics(Publisher.class, ByteBuffer.class), null, Collections.emptyMap());
    assertSame(source, output);
}
Example 8
Project: MULE-master  File: ResponseAssertionMessageProcessor.java View source code
@Override
public Publisher<Event> apply(Publisher<Event> publisher) {
    Flux<Event> flux = from(publisher).map( event -> {
        try {
            return processRequest(event);
        } catch (MuleException e) {
            throw propagate(new MessagingException(event, e));
        }
    });
    flux = from(flux.transform(next));
    return flux.map( event -> {
        try {
            return processResponse(event);
        } catch (MuleException e) {
            throw propagate(new MessagingException(event, e));
        }
    });
}
Example 9
Project: spring-data-redis-master  File: LettuceReactiveClusterStringCommands.java View source code
/* (non-Javadoc)
	 * @see org.springframework.data.redis.connection.lettuce.LettuceReactiveStringCommands#bitOp(org.reactivestreams.Publisher)
	 */
@Override
public Flux<ReactiveRedisConnection.NumericResponse<BitOpCommand, Long>> bitOp(Publisher<BitOpCommand> commands) {
    return getConnection().execute( cmd -> Flux.from(commands).flatMap( command -> {
        List<ByteBuffer> keys = new ArrayList<>(command.getKeys());
        keys.add(command.getDestinationKey());
        if (ClusterSlotHashUtil.isSameSlotForAllKeys(keys)) {
            return super.bitOp(Mono.just(command));
        }
        return Mono.error(new InvalidDataAccessApiUsageException("All keys must map to the same slot for BITOP command."));
    }));
}
Example 10
Project: microservices-event-sourcing-master  File: OrderServiceV1.java View source code
public Order getOrder(String orderId, Boolean validate) {
    // 获取订单
    Order order = orderRepositroy.findOne(orderId);
    if (validate) {
        // 验证事件对应的订单的账户号(account number)属于用户
        try {
            validateAccountNumber(order.getAccountNumber());
        } catch (Exception e) {
            return null;
        }
    }
    Flux<OrderEvent> orderEvents = Flux.fromStream(orderEventRepository.findOrderEventsByOrderId(orderId));
    // 聚合订单状态
    return orderEvents.takeWhile( orderEvent -> orderEvent.getType() != OrderEventType.DELIVERED).reduceWith(() -> order, Order::incorporate).get();
}
Example 11
Project: java-buildpack-system-test-master  File: ServiceBindingTestExecutionListener.java View source code
@Override
public void afterTestClass(TestContext testContext) {
    getServiceType(testContext).ifPresent( serviceType -> {
        Collection<Application> applications = getApplications(testContext);
        ServiceInstance serviceInstance = getServiceInstance(testContext, serviceType);
        Flux.fromIterable(applications).flatMap(( application) -> serviceInstance.unbind(application).doOnError( t -> this.logger.warn("Error while unbinding: {}", t.getMessage())).retryWhen(DelayUtils.exponentialBackOffError(Duration.ofSeconds(1), Duration.ofSeconds(10), Duration.ofMinutes(1)))).then().block(Duration.ofMinutes(1));
    });
}