Reactive Programming in Java: How, Why, and Is It Worth Doing? Part II. Reactivity
At the RIT++ 2020 conference, our Luxoft Training expert and trainer Vladimir Sonkin talked about various tricks to manage asynchronous data flows and approaches to them and showed some examples where you might need reactivity and what it could provide.
Reactivity
This scheme shows various streaming technologies that have been added to different Java versions. As we can see, the Reactive Streams specification is on top: it does not replace everything that was there before but adds the highest level of abstraction, which makes it easy and efficient in use. Let’s try to understand that.
Remember this pattern. We have subscribers and something for which they subscribe. Twitter is an example here, but you can subscribe to any community or person and then get updates on any social network. Once subscribed, all subscribers receive notifications when a new message appears. This is a basic pattern.
In this scheme, there are:
- Publishers — those who publish new messages;
- Observers — those who are subscribed to them. In the case of reactive streams, observers are usually called Subscribers. These are two different terms for essentially the same thing. Most communities use the terms Publisher/Subscriber.
We have a smoke detector and a thermometer. Once there is too much smoke and/or the temperature is too high, the respective sensors’ values increase. When temperature and smoke values exceed a certain threshold, the bell rings, and the alarm signals turn on.
If we had used a traditional (non reactive) approach, we would write code that interrogates the smoke detector and temperature sensor every five minutes and turns the alarm bell on or off. In the case of the reactive approach, however, this is done by a reactive framework, and we just set conditions: alarm is on when the smoke detector value is above X, and the temperature is above Y. It works every time a new event arrives.
A data thread goes from the smoke detector: for example, value 10, then 12, etc. The temperature could change too, it is another data thread — 20, 25, 15. Every time a new value appears, the result is recalculated, which leads to turning the alarm on or off. We should just set a condition under which the alarm must turn on.