Observer pattern
medium 50 minDecouple a state-holding subject from its dependents: they register, and the subject notifies everyone on its list when something changes.
Watch lesson4:58
Where it shows up
The same pattern appears across everyday software.
DOM events
`addEventListener` registers a function on an element. The DOM standard goes through a clone of the list, skips listeners that were removed meanwhile, and reports an exception without stopping the others: the rules of our round.
Node EventEmitter
Listeners are called synchronously in the order of registration. An `error` event without a listener is thrown and ends the process, and too many listeners for one event cause a warning about a possible leak.
Django signals
Receivers connect to signals such as post_save. They are stored as weak references by default, and `send_robust` catches errors of receivers while `send` lets them through.
Android LiveData
An observable value that knows lifecycles. Only observers in an active lifecycle state are updated, and observers clean up after themselves when their lifecycle is destroyed.
Qt signals and slots
Objects emit signals, connected slots are called. When sender or receiver is destroyed, the connection is removed automatically.
Redux store
`subscribe` adds a listener that is called whenever an action is dispatched. It receives no data and calls `getState`: the pull model. It returns a function that unsubscribes.
React useSyncExternalStore
Takes a `subscribe` function, which must return a function to unsubscribe, and a function that reads a snapshot. A component observes any store without tearing.
Java Flow
Publisher, Subscriber, Subscription and Processor since Java 9. The subscriber requests a number of items, so it is never flooded.
Java PropertyChangeSupport
A helper that a bean owns instead of inheriting: it keeps listeners, is documented as thread-safe, and stays silent when the old and the new value are equal and not null.
Spring transactional events
`@TransactionalEventListener` binds a listener to a phase of the transaction, by default after the commit.
Kubernetes watch
Clients list objects and then watch for changes from a resource version on. Controllers are observers across a network that can continue after a broken connection.
RxJS and reactive streams
RxJS extends Observer to values over time, with operators to filter, transform, merge and slow down sequences of events.