Reactive Programming in Java: How, Why, and Is It Worth Doing? Reactive Streams spec
Reactive Streams spec
If we look at our example from the Twitter picture, we can say that:
Publisher is the girl who tweets;
Subscriber is a subscriber. The Subscriber determines what to do if:
- We started listening to the stream (onSubscribe). Once we subscribed successfully, this function will be called
- Another value appeared in the stream (onNext)
- An error occurred (onError)
- The stream is completed (onComplete)
Subscription — we have a subscription which we can cancel (cancel) or request a certain number of values (request(long n)). We can define behavior for each next value or can take values manually.
Processor is both Subscriber and Publisher. It receives some values and puts them somewhere.
If you want to subscribe to something, call Subscribe and then receive updates every time. You can request them manually by using request. Or you can define behavior when a new message arrives (onNext): what to do if a new message appeared, what to do if an error occurred, and what to do if the Publisher completed the stream. We can define these callbacks or cancel.
PUSH / PULL Models
There are two stream models:
Push model — when there is “pushing” of values.
Pull model — when you make a request by yourself.
For instance, you don't want to subscribe, as there is too much information, but you want to visit the site and read the news.
For the Push model, we define callbacks, i.e., functions that will be called when the following message arrives, and for the Pull model, we can use the request method when we want to learn something new.
The Pull model is essential for Backpressure. What’s that?
You could be spammed by your subscriptions. In that case, you are unable to read them all, and there's a chance that you may lose critical data — they would just get lost in that message flow. When, due to a considerable information flow, the Subscriber cannot handle everything published by the Publisher, we have Backpressure.