The publishOn operator

In a nutshell, the publishOn operator allows the moving part of runtime execution to a specified worker.

We avoid using the word Thread here since the underlying mechanism of the Scheduler may enqueue work to the same Thread, but the execution job may be done by a different worker from a Scheduler instance perspective. 

In order to specify the worker that should process elements at runtime, Reactor introduces a specific abstraction for that purpose, called SchedulerScheduler is an interface that represents a worker or pool of workers in Project Reactor. We are going to cover Scheduler later in this chapter, but for now, we will just mention that this interface is used in order to choose a specific worker for the current stream. In order to better understand how we can use the publishOn operator, let's consider the following code sample:

Scheduler scheduler = ...;        // (1)
                                  //
Flux.range(0, 100)                // (2) ¯|
    .map(String::valueOf)         // (3)  |> Thread Main
    .filter(s -> s.length() > 1)  // (4) _|

    .publishOn(scheduler)         // (5)

    .map(this::calculateHash)     // (6) ¯|
    .map(this::doBusinessLogic)   // (7)  |> Scheduler Thread
    .subscribe()                  // (8) _|

As we can see from the preceding code, the operations on elements from step 2 to step 4 take place on the Thread Main where the execution after the publishOn operator is on a different Scheduler worker. This means that the calculation of the hash takes place on Thread A, so calculateHash and doBusinessLogic are executed on a different worker from the Thread Main worker. If we look at the publishOn operator from an execution model perspective, we can see the following flow:

Figure 4.9. Representation of Reactor's publishOn operator internals

As we may notice, the focus of the publishOn operator is on runtime execution. Under the hood, the publishOn operator keeps a queue to which it supplies new elements so that a dedicated worker can consume messages and process them one by one. In this example, we have shown that work is running on the separate Thread, so our execution is split by an asynchronous boundary. So, now, we kind of have two independently processed parts of the flow. One important thing that we need to highlight is that all elements in a Reactive Stream are processed one by one (not concurrently) so that we may always define a strict order for all events. This property is also called serializability. This means that, once the element comes to publishOn, it will be enqueued, and once its turn has come, it will be dequeued and processed. Note that only one worker is dedicated to processing the queue, so the order of the elements is always predictable.

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

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