Java
Publisher and Subscriber
Learn Publisher and Subscriber roles.
Publisher and Subscriber interaction
The flow starts with a call to Publisher.subscribe. The Publisher first gives a Subscription through Subscriber.onSubscribe. When the Subscriber calls request on this Subscription, the Publisher sends items with onNext.
The flow ends in two ways: onComplete signals a successful end, and onError signals a failure. After either, no more onNext arrives. This contract keeps the flow predictable; the Subscriber always follows the same lifecycle.
Request and delivery
The Subscriber asks for n items with request(n). The Publisher sends that many items with onNext. Sending more before another request violates the contract; this is the basis of backpressure.
Example: request(1) asks for one item; after onNext arrives, request(1) can be called again. This suits a Subscriber that processes one item at a time. request(Long.MAX_VALUE) means an unbounded request, which effectively disables backpressure.
Exercise Sum two items
Define a SumPublisher class that implements Publisher<Integer>. The request method inside subscribe calls s.onNext(10), s.onNext(20), and s.onComplete(). In main, an anonymous Subscriber: onSubscribe calls request(Long.MAX_VALUE), onNext does sum += v, and onComplete prints the sum with System.out.println(sum).
Show example solution
import java.util.concurrent.Flow.*;
class SumPublisher implements Publisher<Integer> {
public void subscribe(Subscriber<? super Integer> s) {
s.onSubscribe(new Subscription() {
public void request(long n) { s.onNext(10); s.onNext(20); s.onComplete(); }
public void cancel() { }
});
}
}
public class SumDemo {
public static void main(String[] args) {
new SumPublisher().subscribe(new Subscriber<Integer>() {
int sum;
public void onSubscribe(Subscription s) { s.request(Long.MAX_VALUE); }
public void onNext(Integer v) { sum += v; }
public void onError(Throwable t) { }
public void onComplete() { System.out.println(sum); }
});
}
}
Test yourself
-
Match the lifecycle
- subscribe
- Starts subscription
- onSubscribe
- Receives Subscription
- onNext
- Receives an item
- onComplete
- Flow ended
-
What does the Publisher's subscribe method take?
- A Subscriber
- A String
- An int
- A Subscription
Show answer
A Subscriber — subscribe takes a Subscriber and starts the flow.
-
Define the onNext method
public void ____(String v) { System.out.println(v); }
Show answer
public void onNext(String v) { System.out.println(v); }
Next lesson: SubmissionPublisher