Sub topic 2
The Reactive Streams contract
This chapter assumes you know Java lambdas and generics, and that you have read the previous chapter on blocking and non-blocking request handling. Reactor and WebFlux are built on one small specification. Knowing it explains why pipelines behave the way they do.
Four interfaces
Reactive Streams is a specification for passing a stream of items between components asynchronously. It defines four interfaces, in the org.reactivestreams package.
Publisher<T>is a source of items. It has one method,subscribe(Subscriber<? super T>).Subscriber<T>receives items. It has four methods:onSubscribe,onNext,onError, andonComplete.Subscriptionlinks one publisher to one subscriber. It hasrequest(long n)andcancel().Processor<T, R>is both a subscriber and a publisher. It sits in the middle of a chain.
Mono and Flux both implement Publisher. Operators such as map return a new publisher that wraps the previous one.
The signal sequence
A subscriber sees signals in a fixed order:
onSubscribe, then zero or more onNext, then at most one terminal signal, either onError or onComplete.
The publisher may send only as many onNext signals as the subscriber has requested in total. That is the whole backpressure mechanism, and a later chapter covers it in detail. Here the point is the direction of control. Demand flows upstream through request(n), and data flows downstream through onNext.
Rules that matter in practice
The specification contains many rules. These are the ones that affect how you write code:
- Signals to one subscriber must be serial.
onNextcalls never overlap, though they may happen on different threads. - After
onErrororonComplete, nothing more is sent. A pipeline that fails is finished. nullis never a valid item. This is whyMono.just(null)throws, and why an empty result isMono.empty().request(n)requiresn > 0. Any other value produces anonErrorwith anIllegalArgumentException.- After
cancel(), the publisher should stop sending soon, but a few signals may still arrive.
Watching the contract run
BaseSubscriber is a Reactor class that implements Subscriber and gives you hooks for each signal. This example requests one item at a time:
import org.reactivestreams.Subscription;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
public class ContractDemo {
public static void main(String[] args) {
Flux.just("a", "b", "c").subscribe(new BaseSubscriber<String>() {
@Override
protected void hookOnSubscribe(Subscription subscription) {
System.out.println("subscribed");
request(1);
}
@Override
protected void hookOnNext(String value) {
System.out.println("next " + value);
request(1);
}
@Override
protected void hookOnComplete() {
System.out.println("complete");
}
@Override
protected void hookOnError(Throwable error) {
System.out.println("error " + error);
}
});
}
}The output is subscribed, next a, next b, next c, complete. Nothing is emitted until the first request(1).
The usual subscribe(System.out::println) form hides all of this. Reactor's default subscriber requests an unbounded number of items right away.
Common errors
- Implementing
Publisheryourself. Getting every rule right is hard. Build publishers withFlux.create,Flux.generate, orMono.fromCallable, which enforce the rules for you. - Expecting work without a subscriber. Declaring a pipeline sends no signals. Something must subscribe. In WebFlux, the framework subscribes for you when you return a
MonoorFluxfrom a handler. - Ignoring
onError. If you subscribe with only an item consumer, Reactor reports an unhandled error. Chapter-level error handling comes later, but always know who handles the terminal signal. - Assuming one thread. The serial rule does not mean a single thread. Do not keep thread-local state across signals.
Exercise
A publisher has sent onComplete to a subscriber. Can it later send another onNext to that same subscriber? Why does the answer matter for error handling?
Show answer
No. onComplete and onError are terminal, and nothing may follow them. Because of this, an error ends the stream, so recovering from an error means switching to a different publisher, for example with onErrorResume, instead of resuming the failed one.