Java
Flow API
Learn reactive streams with the Java 9 Flow API.
The Flow API
Since Java 9, Reactive Streams has been part of the platform through the java.util.concurrent.Flow class. This API defines asynchronous data flow with three standard interfaces: a Publisher produces data, a Subscriber consumes it, and a Subscription controls the flow.
The flow direction is from Publisher to Subscriber; but the Subscriber states how much data it wants with request. This is called backpressure and stops the producer from outrunning the consumer. The Flow API lets frameworks agree on a common base.
The roles of the three interfaces
A Publisher has a single method: subscribe(Subscriber). It registers a subscriber. A Subscriber has four methods: onSubscribe receives the Subscription, onNext receives an item, onError an error, and onComplete the end of the flow.
A Subscription requests n items with request(n) and cancels the flow with cancel. This structure allows both synchronous and asynchronous delivery. What matters is the contract; timing is implementation-dependent.
Exercise Send data with a synchronous Publisher
Define an OnePublisher class that implements Publisher<String>. Its subscribe method calls onSubscribe; the Subscription's request method calls s.onNext("hello") and s.onComplete(). In main, create an anonymous Subscriber with new OnePublisher().subscribe(...); onSubscribe calls request(1), and onNext prints the value with System.out.println.
Show example solution
import java.util.concurrent.Flow.*;
class OnePublisher implements Publisher<String> {
public void subscribe(Subscriber<? super String> s) {
s.onSubscribe(new Subscription() {
public void request(long n) { s.onNext("hello"); s.onComplete(); }
public void cancel() { }
});
}
}
public class FlowDemo {
public static void main(String[] args) {
new OnePublisher().subscribe(new Subscriber<String>() {
public void onSubscribe(Subscription s) { s.request(1); }
public void onNext(String v) { System.out.println(v); }
public void onError(Throwable t) { }
public void onComplete() { }
});
}
}
Test yourself
-
In which package is Java's built-in Reactive Streams API?
- java.util.stream
- java.io
- java.nio
- java.util.concurrent.Flow
Show answer
java.util.concurrent.Flow — The Flow class holds the Reactive Streams interfaces.
-
Complete the Subscriber import
import java.util.concurrent.____.Subscriber;
Show answer
import java.util.concurrent.Flow.Subscriber;
-
Match the Flow interfaces
- Publisher
- Produces data
- Subscriber
- Consumes data
- Subscription
- Controls the flow
- onNext
- Item notification
Next lesson: Publisher and Subscriber