Combining Reactive Streams

Of course, Project Reactor allows the combining of many incoming streams into one outgoing stream. The named operators have many overrides but perform the following transformations:

  • The concat operator concatenates all sources by forwarding received elements downstream. When the operator concatenates two streams, at first, it consumes and resends all elements of the first stream, then does the same for the second.
  • The merge operator merges data from upstream sequences into one downstream sequence. Unlike  the concat operator, upstream sources are subscribed to eagerly (at the same time).
  • The zip operator subscribes to all upstreams, waits for all sources to emit one element and then combines received elements into an output element. In Chapter 2, Reactive Programming in Spring - Basic Concepts, we described how zip works in detail. In Reactor, the zip operator may operate not only with reactive publishers but also with an Iterable container. For that purpose, we can use the zipWithIterable operator.
  • The combineLatest operator works similarly to the zip operator. However, it generates a new value as soon as at least one upstream source emits a value.

Let's concatenate a couple of streams:

Flux.concat(
Flux.range(1, 3),
Flux.range(4, 2),
Flux.range(6, 5)
).subscribe(e -> log.info("onNext: {}", e));

Obviously, the preceding code in the result generates values from 1 to 10 ([1, 2 , 3] + [4, 5] + [6, 7, 8, 9, 10]).

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

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