Dealing with time

Reactive programming is asynchronous, so it inherently assumes the presence of the arrow of time.

With Project Reactor, we can generate events based on a duration with the interval operator, delay elements with the delayElements operator, and delay all signals with the delaySequence operator. In this chapter, we have already used a couple of these operators.

We have already discussed how data buffering and windowing can happen based on configured timeouts (the buffer(Duration) and window(Window) operators). Reactor's API allows you to react to some time-related events, such as with the previously described timestamp and timeout operators. Similar to timestamp, the elapsed operator measures the time interval from the previous event. Let's consider the following code:

Flux.range(0, 5)
.delayElements(Duration.ofMillis(100))
.elapsed()
.subscribe(e -> log.info("Elapsed {} ms: {}", e.getT1(), e.getT2()));

Here, we generate events every 100 milliseconds. Let's look at the log output:

Elapsed 151 ms: 0
Elapsed 105 ms: 1
Elapsed 105 ms: 2
Elapsed 103 ms: 3
Elapsed 102 ms: 4

From the preceding output, it is evident that events do not arrive precisely within the 100 millisecond interval. This happens because Reactor uses Java's ScheduledExecutorService for scheduled events, which itself does not give guarantees about the exact delay. So, we should be careful not to demand too precise time (real-time) intervals from the Reactor library.

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

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