Hot and cold streams

When talking about reactive publishers, we may distinguish two types of publishers—hot and cold.

Cold publishers behave in such a way that, whenever a subscriber appears, all of the sequence data is generated for that subscriber. Also, with a cold publisher, no data would be generated without a subscriber. For example, the following code represents the behavior of a cold publisher:

Flux<String> coldPublisher = Flux.defer(() -> {
log.info("Generating new items");
return Flux.just(UUID.randomUUID().toString());
});

log.info("No data was generated so far");
coldPublisher.subscribe(e -> log.info("onNext: {}", e));
coldPublisher.subscribe(e -> log.info("onNext: {}", e));
log.info("Data was generated twice for two subscribers");

The preceding code generates the following output:

No data was generated so far
Generating new items
onNext: 63c8d67e-86e2-48fc-80a8-a9c039b3909c
Generating new items
onNext: 52232746-9b19-4b5e-b6b9-b0a2fa76079a
Data was generated twice for two subscribers

As we can see, a new sequence is generated whenever a subscriber appears—these semantics may represent HTTP requests. No call is made until no one is interested in the result and each new subscriber triggers an HTTP request.

On the other hand, data generation in hot publishers does not depend on the presence of a subscriber. So, a hot publisher may start producing elements way before the first subscriber. Also, when a subscriber appears, a hot publisher may not send the previously generated values, only new ones. Such semantics represent data broadcast scenarios. For example, a hot publisher may broadcast updates to its subscribers regarding current oil prices, as soon as the prices change. However, when a subscriber arrives, it receives only future updates, not the history of previous prices. Most hot publishers in the Reactor library extend the Processor interface. Reactor's processors are covered in the Processors section. However, the just factory method generates a hot publisher as its values are calculated only once when the publisher is built, and are not recalculated when a new subscriber arrives.

We may transform just into a cold publisher by wrapping it in defer. That way, even though just generates values on its initialization, such an initialization will only happen when a new subscription appears. The latter behavior is dictated by the defer factory method.

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

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