Publisher and Subscriber
- Java course
- Expert
- Lesson 20/46
- 5 min
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.
Practice 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).
Starter code
// Define the SumPublisher class
// Sum with onNext
// Print in onCompleteSample 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); }
});
}
}Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the lifecycle
| Term | Meaning |
|---|---|
subscribe |
Starts subscription |
onSubscribe |
Receives Subscription |
onNext |
Receives an item |
onComplete |
Flow ended |
2 What does the Publisher's subscribe method take?
- A Subscriber Correct answer
- A String
- An int
- A Subscription
Explanation: subscribe takes a Subscriber and starts the flow.
3 Define the onNext method
public void ____(String v) { System.out.println(v); }
public void onNext(String v) { System.out.println(v); }
Explanation: onNext notifies a Subscriber of an item.