Factory methods – push and create

The push factory method allows for the programmatical creation of a Flux instance by adapting a single-threaded producer. This approach is useful for adapting an async, single-threaded, multi-valued API without worrying about backpressure and cancellation. Both aspects are covered by queueing signals if the subscriber can't handle the load. Let's look at the following code:

Flux.push(emitter -> IntStream                                     // (1)
.range(2000, 3000) // (1.1)
.forEach(emitter::next)) // (1.2)
.delayElements(Duration.ofMillis(1)) // (2)
.subscribe(e -> log.info("onNext: {}", e)); // (3)

Let's look at the preceding code:

  1. Here, we use the push factory method to adapt some existing API to the reactive paradigm. For the sake of simplicity, here, we use the Java Stream API to generate 1000 integer elements (1.1) and send them to the emitter object of the FluxSink type (1.2). Inside the push method, we do not care about backpressure and cancellation, as these functionalities are covered by the push method itself. 
  2. Let's delay each element in the stream to simulate a backpressure situation.
  3. Here, we subscribe to the onNext events.

The push factory method can be handy for adapting an asynchronous API with the default backpressure and cancellation strategies.

Also, there is the create factory method, which behaves similarly to the push factory method. However, this allows forthe sending of events from different threads as it additionally serializes the FluxSink instance. Both methods allow for the overriding of the overflow strategy and also enable resource cleanup by registering additional handlers, as in the following code:

Flux.create(emitter -> {
emitter.onDispose(() -> log.info("Disposed"));
// push events to emitter
})
.subscribe(e -> log.info("onNext: {}", e));
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.73.207