Java 9 (Part 5): Flow With the New Reactive Streams, First Look
The Reactive streams API will undergo a name change in Java 9. This quick guide will walk you through everything you need to know about it.
Join the DZone community and get the full member experience.
Join For FreeWelcome back to my Java 9 series! We are going to cover another cool and new concept in Java 9 — a concise interface for Reactive streams, which contains the ability for non-blocking back pressure. You see, Reactive streams are all around us in all up-to-date languages and libraries. The main challenge, however, in Reactive streams is not the implementation, but a concise interface. Let's see how Java 9 will handle it.
Java 9 Reactive Streams
The main components of Java 9 Reactive streams are:
- Publisher
- Subscriber
- Subscription
In short, the subscriber subscribes to the publisher on a subscription to receive the stream.
For that, we have multiple methods such as:
- Publisher::subscribe
- Subscriber::onNext
- Subscriber::onSubscription
- Subsription::request
The names are rather self explanatory which is great.
Implementing Flow
By now, you should call Reactive streams –> Flow. In order to implement such a stream, you need to implement: Publisher, Subscriber, Subscription.
Create the publisher:
SubmissionPublisher<Integer> publisher = new SubmissionPublisher<>();
Create the subscriber:
public class MySubscriber implements Flow.Subscriber<String> {
private Subscription subscription;
@Override public void onSubscribe(Flow.Subscription subscription) { // implemnet }
@Override public void onNext(Integer item) { // implemnet }
@Override public void onError(Throable t) { // implemnet }
@Override public void onComplete() { // implemnet }
}
So all we needed to do was to create a publisher, then create a subscriber. Note that the subscriber should have a subscription member. Then, the Subscriber implements all the methods related to the flow API:
- onSubscribe
- onNext
- onError
- onComplete
Summary
In part 5, we saw that the Reactive streams API has become much better and is called the Flow API. This API is concise and includes three main components: publisher, subscriber, and subscription, with subscriber implementing the methods for receiving the stream and notifying on errors.
Opinions expressed by DZone contributors are their own.
Comments