Ajitesh Tiwari
Posted on March 23, 2018
Java 9 Flow API
Flow API is Java's official support for Reactive Streams Specification. It is a combination of both Iterator(Pull) and Observer(Push) patterns.
The Flow API is an inter operation specification and not an end-user API like RxJava.
If you are a developer(even an outdated one :D), you must have surely heard about reactive-streams, non blocking IO, asynchronous calls, etc.
So why Reactive?
Consider it as a secretary in a office -
- If they makes you wait for meeting their boss - that's normal way.
- If they asks you to go do something else and they contact you when their boss is free for meeting - that's the reactive way.
People generally tend to think any reactive programming as improvement in speed, but it is not true. Considering both scenarios above you have to spend equal time for meeting her boss (so no improvement in speed), but you can be more productive in the second approach.
Reactive programming increases scalability and stability but not speed.
Flow API
Flow API consists of 4 basic interfaces -
- Subscriber - The Subscriber subscribes to the Publisher for the callbacks.
- Publisher - The publisher publishes the stream of data items to the registered subscribers.
- Subscription - Link between publisher and subscriber.
- Processor - The processor sits between the Publisher and Subscriber, and transforms one stream to another.
Now it's time for some hands-on with our new Flow API
Let's create a basic subscriber which asks for one data object, prints it and asks for one more.
Now let's quickly use a publisher implementation provided by Java (SubmissionPublisher) to complete our session.
And here is our sweet output -
Here you can easily see how the submit(T item) function of publisher invokes onNext(T item) function of subscriber.
But it wouldn't have been possible without request(long n) function of the subscription.
The delay of 1 sec helps us see the reactive magic happening. Although it's no magic, just some code written by really smart people.
Source Code
Posted on March 23, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.