Video in progress
How do Publisher/Subscriber in Reactive Streams differ from the classic Observer pattern?
In classic Observer, the subject pushes events as fast as it likes, even if the listener can't keep up. In Reactive Streams, the subscriber says how many items it is ready to take with request(n), which is backpressure. On top of that, stream completion and errors are part of the contract.
📖 Answer
In classic Observer, onEvent() is called and that's it. If the listener is slow, there are two options: the publisher's thread ends up waiting, or events pile up in a queue somewhere and memory grows.
The Reactive Streams contract (in the JDK, java.util.concurrent.Flow) consists of four signals:
public interface Subscriber<T> {
void onSubscribe(Flow.Subscription s); // s.request(n) / s.cancel()
void onNext(T item);
void onError(Throwable t);
void onComplete();
}
A publisher can't send more onNext calls than the subscriber has asked for. The subscriber says request(32), and once it has processed those 32, it asks again. So the consumer controls the pace. There are also two things Observer doesn't have: the stream is finished (onComplete) and the stream stopped with an error (onError), after which no further signal arrives.
Don't implement this contract yourself: it has many subtle rules. Use Project Reactor (Flux, Mono) or RxJava. If the source doesn't understand backpressure (for example user clicks or an external WebSocket), you pick the strategy yourself: onBackpressureBuffer(10_000), onBackpressureDrop(), onBackpressureLatest().
When you need it: when the stream has many elements and the consumer may be slower, such as reading from Kafka and writing to a database, or streaming a large file. For a simple "order paid, send an email", Spring's ordinary events are enough.
Sign up to mark studied questions and save your progress.