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

The following examples show how to use reactor.core.publisher.Flux#create() . 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: LoadBalancedRSocketMonoTest.java    From rsocket-java with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10_000L)
public void testRefreshesSocketsOnSelectBeforeReturningFailedAfterNewFactoriesDelivered() {
  TestingRSocket socket = new TestingRSocket(Function.identity());

  CompletableFuture<RSocketSupplier> laterSupplier = new CompletableFuture<>();
  Flux<List<RSocketSupplier>> factories =
      Flux.create(
          s -> {
            s.next(Collections.emptyList());

            laterSupplier.handle(
                (RSocketSupplier result, Throwable t) -> {
                  s.next(Collections.singletonList(result));
                  return null;
                });
          });

  LoadBalancedRSocketMono balancer = LoadBalancedRSocketMono.create(factories);

  Assert.assertEquals(0.0, balancer.availability(), 0);

  laterSupplier.complete(succeedingFactory(socket));
  balancer.rSocketMono.block();

  Assert.assertEquals(1.0, balancer.availability(), 0);
}
 
Example 2
Source File: RetryHandlerBuilderTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private Flux<String> fluxOf(Object... items) {
    AtomicInteger pos = new AtomicInteger();
    return Flux.create(sink -> {
        for (int i = pos.get(); i < items.length; i++) {
            pos.incrementAndGet();
            Object item = items[i];

            if (item instanceof Throwable) {
                sink.error((Throwable) item);
                return;
            }
            sink.next((String) item);
        }
        sink.complete();
    });
}
 
Example 3
Source File: R023_CallbackToFlux.java    From reactor-workshop with GNU General Public License v3.0 6 votes vote down vote up
/**
 * TODO terminate the stream when <code>null</code> is received from callback.
 * Hint: <code>sink.complete()</code>
 */
@Test
public void handleNullAsEndOfStream() throws Exception {
	//when
	final Flux<Email> emails = Flux
			.create(sink ->
					inbox.read("[email protected]", e -> {
						if (e != null) {
							sink.next(e);
						} else {
							sink.complete();
						}
					}));

	//then
	emails
			.as(StepVerifier::create)
			.expectNextCount(2)
			.verifyComplete();
}
 
Example 4
Source File: TcpController.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
@GetMapping(value = "/server/{id}/_subscribe/{type}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<TcpClientMessage> serverSubscribe(@PathVariable String id, @PathVariable PayloadType type) {
    return Flux.create(sink -> {
        sink.onDispose(networkManager.<TcpServer>getNetwork(DefaultNetworkType.TCP_SERVER, id)
            .flatMapMany(TcpServer::handleConnection)
            .flatMap(client -> {
                String address = client.getRemoteAddress().toString();
                sink.next(new TcpClientMessage(address, "已建立连接"));
                client.onDisconnect(() -> sink.next(new TcpClientMessage(address, "已断开连接")));
                return client
                    .subscribe()
                    .map(msg -> new TcpClientMessage(address, type.read(msg.getPayload())));

            })
            .subscriberContext(sink.currentContext())
            .subscribe(sink::next));
    });
}
 
Example 5
Source File: Archaius2Ext.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
/**
 * Observe property value changes. Emits current value on subscriptions.
 */
public static <T> Flux<T> watch(Property<T> property) {
    Flux<T> observer = Flux.create(emitter -> {
        Property.Subscription subscription = property.subscribe(emitter::next);
        emitter.onCancel(subscription::unsubscribe);
    });

    return Flux.just(property.get()).concatWith(observer);
}
 
Example 6
Source File: FluxConverter.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
public <X> Flux fromCompletionStage(CompletionStage<X> cs) {
    return Flux.create(sink -> cs.whenComplete((X v, Throwable e) -> {
        if (e != null) {
            sink.error(e instanceof CompletionException ? e.getCause() : e);
        } else if (v != null) {
            sink.next(v);
            sink.complete();
        } else {
            sink.complete();
        }
    }));
}
 
Example 7
Source File: MyApi.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<String> fluxEcho(String message) {
    return Flux.create(emitter -> {
        emitter.next(buildReply(message));
        emitter.complete();
    });
}
 
Example 8
Source File: RedissonTimeSeriesReactive.java    From redisson with Apache License 2.0 5 votes vote down vote up
public Publisher<V> iterator() {
    return Flux.create(new SetReactiveIterator<V>() {
        @Override
        protected RFuture<ListScanResult<Object>> scanIterator(RedisClient client, long nextIterPos) {
            return ((RedissonTimeSeries) instance).scanIteratorAsync(instance.getName(), client, nextIterPos, null, 10);
        }
    });
}
 
Example 9
Source File: QuotaEventEmitter.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
public Flux<EvictionEvent> events(boolean includeSnapshot) {
    return Flux.create(sink -> {
        Preconditions.checkState(scheduleReference != null && !scheduleReference.isClosed());
        eventSubscriberSinks.add(new SinkHolder(sink, includeSnapshot));
        sink.onDispose(() -> eventSubscriberSinks.remove(sink));
    });
}
 
Example 10
Source File: R023_CallbackToFlux.java    From reactor-workshop with GNU General Public License v3.0 5 votes vote down vote up
/**
 * TODO use {@link Flux#as(Function)} operator with {@link #toList(Flux)} method
 */
@Test
public void asOperator() throws Exception {
	//given
	final Flux<Email> foo = Flux.create(sink ->
			inbox.read("[email protected]", sink::next));

	//when
	final List<Email> emails = toList(foo);

	//then
	assertThat(emails).hasSize(3);
}
 
Example 11
Source File: FluxSinkApplication.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
Flux<ServerSentEvent<Map>> processor(final List<FluxSink<ServerSentEvent<Map>>> subscribers) {
  return Flux.create(
      fluxSink -> subscribers.add(
          fluxSink.onCancel(() -> subscribers.remove(fluxSink))
                  .onDispose(() -> log.debug("disposing..."))
                  .onRequest(i -> log.debug("{} subscribers on request", subscribers.size()))));
}
 
Example 12
Source File: GrpcRetryTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Flux<Integer> newThreeErrorFlux() {
    return Flux.create(new Consumer<FluxSink<Integer>>() {
        int count = 3;
        @Override
        public void accept(FluxSink<Integer> emitter) {
            if (count > 0) {
                emitter.error(new Throwable("Not yet!"));
                count--;
            } else {
                emitter.next(0);
                emitter.complete();
            }
        }
    }, FluxSink.OverflowStrategy.BUFFER);
}
 
Example 13
Source File: StateStoreRepository.java    From football-events with MIT License 5 votes vote down vote up
public Flux<T> findAll() {
    return Flux.create(sink -> {
        var iterator = store().all();

        while (iterator.hasNext()) {
            sink.next(iterator.next().value);
        }
        iterator.close();
        sink.complete();
    });
}
 
Example 14
Source File: GuideTests.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void producingCreate() {
	Flux<String> bridge = Flux.create(sink -> {
		myEventProcessor.register( // <4>
				new MyEventListener<String>() { // <1>

					public void onDataChunk(List<String> chunk) {
						for(String s : chunk) {
							sink.next(s); // <2>
						}
					}

					public void processComplete() {
						sink.complete(); // <3>
					}
				});
	});

	StepVerifier.withVirtualTime(() -> bridge)
                .expectSubscription()
                .expectNoEvent(Duration.ofSeconds(10))
                .then(() -> myEventProcessor.dataChunk("foo", "bar", "baz"))
                .expectNext("foo", "bar", "baz")
                .expectNoEvent(Duration.ofSeconds(10))
                .then(() -> myEventProcessor.processComplete())
                .verifyComplete();
}
 
Example 15
Source File: SourceToFunctionsSupportTests.java    From spring-cloud-stream with Apache License 2.0 5 votes vote down vote up
@Bean
public Supplier<Flux<String>> numberReactive() {
	return () -> Flux.create(emitter -> {
		for (int i = 0; i < 3; i++) {
			emitter.next(String.valueOf(i));
		}
	});
}
 
Example 16
Source File: BlobCodecTest.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
@Override
public Flux<ByteBuffer> stream() {
    return Flux.create(sink -> {
        for (byte[] value : values) {
            if (sink.isCancelled()) {
                return;
            }

            ByteBuffer buffer = ByteBuffer.allocate(value.length);
            buffer.put(value).flip();
            sink.next(buffer);
        }
        sink.complete();
    });
}
 
Example 17
Source File: FluxToCompletionStageTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
protected Optional<Flux> createInstanceEmittingAMultipleValuesAndFailure(String v1, String v2, RuntimeException e) {
    Flux<String> stream = Flux.create(emitter -> {
        emitter.next(v1);
        emitter.next(v2);
        emitter.error(e);
    });
    return Optional.of(stream);
}
 
Example 18
Source File: HttpRequestOperation.java    From styx with Apache License 2.0 5 votes vote down vote up
public Flux<LiveHttpResponse> execute(NettyConnection nettyConnection) {
    AtomicReference<RequestBodyChunkSubscriber> requestRequestBodyChunkSubscriber = new AtomicReference<>();
    requestTime = System.currentTimeMillis();
    executeCount.incrementAndGet();

    Flux<LiveHttpResponse> responseFlux = Flux.create(sink -> {
        if (nettyConnection.isConnected()) {
            RequestBodyChunkSubscriber bodyChunkSubscriber = new RequestBodyChunkSubscriber(request, nettyConnection);
            requestRequestBodyChunkSubscriber.set(bodyChunkSubscriber);
            addProxyBridgeHandlers(nettyConnection, sink);
            new WriteRequestToOrigin(sink, nettyConnection, request, bodyChunkSubscriber)
                    .write();
            if (requestLoggingEnabled) {
                httpRequestMessageLogger.logRequest(request, nettyConnection.getOrigin());
            }
        } else {
            sink.error(new TransportLostException(nettyConnection.channel(), nettyConnection.getOrigin()));
        }
    });

    if (requestLoggingEnabled) {
        responseFlux = responseFlux
                .doOnNext(response -> {
                    httpRequestMessageLogger.logResponse(request, response);
                });
    }
    return responseFlux.map(response ->
                    Requests.doFinally(response, cause -> {
                        if (nettyConnection.isConnected()) {
                            removeProxyBridgeHandlers(nettyConnection);
                            if (requestIsOngoing(requestRequestBodyChunkSubscriber.get())) {
                                LOGGER.warn("Origin responded too quickly to an ongoing request, or it was cancelled. Connection={}, Request={}.",
                                        new Object[]{nettyConnection.channel(), this.request});
                                nettyConnection.close();
                                requestRequestBodyChunkSubscriber.get().dispose();
                            }
                        }
                    }));
}
 
Example 19
Source File: DataBufferUtils.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Write the given stream of {@link DataBuffer DataBuffers} to the given
 * {@code WritableByteChannel}. Does <strong>not</strong> close the channel
 * when the flux is terminated, and does <strong>not</strong>
 * {@linkplain #release(DataBuffer) release} the data buffers in the source.
 * If releasing is required, then subscribe to the returned {@code Flux}
 * with a {@link #releaseConsumer()}.
 * <p>Note that the writing process does not start until the returned
 * {@code Flux} is subscribed to.
 * @param source the stream of data buffers to be written
 * @param channel the channel to write to
 * @return a Flux containing the same buffers as in {@code source}, that
 * starts the writing process when subscribed to, and that publishes any
 * writing errors and the completion signal
 */
public static Flux<DataBuffer> write(Publisher<DataBuffer> source, WritableByteChannel channel) {
	Assert.notNull(source, "'source' must not be null");
	Assert.notNull(channel, "'channel' must not be null");

	Flux<DataBuffer> flux = Flux.from(source);
	return Flux.create(sink -> {
		WritableByteChannelSubscriber subscriber = new WritableByteChannelSubscriber(sink, channel);
		sink.onDispose(subscriber);
		flux.subscribe(subscriber);
	});
}
 
Example 20
Source File: DataBufferUtils.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Write the given stream of {@link DataBuffer DataBuffers} to the given
 * {@code AsynchronousFileChannel}. Does <strong>not</strong> close the channel
 * when the flux is terminated, and does <strong>not</strong>
 * {@linkplain #release(DataBuffer) release} the data buffers in the source.
 * If releasing is required, then subscribe to the returned {@code Flux} with a
 * {@link #releaseConsumer()}.
 * <p>Note that the writing process does not start until the returned
 * {@code Flux} is subscribed to.
 * @param source the stream of data buffers to be written
 * @param channel the channel to write to
 * @param position file position write write is to begin; must be non-negative
 * @return a flux containing the same buffers as in {@code source}, that
 * starts the writing process when subscribed to, and that publishes any
 * writing errors and the completion signal
 */
public static Flux<DataBuffer> write(
		Publisher<DataBuffer> source, AsynchronousFileChannel channel, long position) {

	Assert.notNull(source, "'source' must not be null");
	Assert.notNull(channel, "'channel' must not be null");
	Assert.isTrue(position >= 0, "'position' must be >= 0");

	Flux<DataBuffer> flux = Flux.from(source);
	return Flux.create(sink -> {
		WriteCompletionHandler handler = new WriteCompletionHandler(sink, channel, position);
		sink.onDispose(handler);
		flux.subscribe(handler);
	});
}