Factory method – generate

The generate factory method is designed to allow for the creation of complicated sequences based on an internal forwarded state of the generator. It requires an initial value and a function, which calculates the next internal state based on the previous one and also sends the onNext signal to a downstream subscriber. For example, let's create a simple Reactive Stream that produces the Fibonacci sequence (1, 1, 2, 3, 5, 8, 13, ...). The code for this task may look as follows:

Flux.generate(                                                     // (1)
() -> Tuples.of(0L, 1L), // (1.1)
(state, sink) -> { //
log.info("generated value: {}", state.getT2()); //
sink.next(state.getT2()); // (1.2)
long newValue = state.getT1() + state.getT2(); //
return Tuples.of(state.getT2(), newValue); // (1.3)
})
.delayElements(Duration.ofMillis(1)) // (2)
.take(7) // (3)
.subscribe(e -> log.info("onNext: {}", e)); // (4)

Let's look at the preceding code:

  1. With the generate factory method, we may create a custom reactive sequence. We use Tuples.of(0L, 1L)  as the initial state of the sequence (1.1). In the generation step, we send the onNext signal by referencing the second value in the state pair (1.2) and recalculate a new state pair based on the next value in the Fibonacci sequence (1.3).
  2. With the delayElements operator, we introduce some latency between onNext signals.
  3.  Here, we take only the first seven elements for the sake of simplicity.
  4. Of course, to trigger sequence generation, we subscribe for events.

The preceding code produces the following output:

generated value: 1
onNext: 1
generated value: 1
onNext: 1
generated value: 2
onNext: 2
generated value: 3
onNext: 3
generated value: 5
onNext: 5
generated value: 8
onNext: 8
generated value: 13
onNext: 13

As we can see in the logs, each new value is synchronously propagated to the subscriber before generating the next one. This approach may be useful for generating different, complicated reactive sequences that require an intermediate state between emissions.

..................Content has been hidden....................

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