Behavioral Event-Subscriber Listener Pub-Sub

Observer

Observer is a behavioral pattern that lets any number of objects register interest in another object's changes and get notified automatically whenever those changes happen.

Complexity
Popularity

Problem

A weather station gathers new sensor readings every few minutes. A phone app, a desktop widget, and a logging service all need to know the instant fresh data lands, but none of them should have to ask the station directly on a timer.

Polling is the naive fix - each consumer calls the station repeatedly and compares against the last value it saw. That wastes cycles when nothing has changed and adds lag between an update and the moment consumers see it. Hardcoding calls from the station to each specific consumer is worse: the station now has to know about the phone app, the widget, and the logger by name, and adding a fourth consumer means editing the station's code.

Solution

Observer gives the object holding the interesting state - the publisher - a guest list it doesn't need to know the contents of in advance. Any object can join that list by subscribing, and any object can leave by unsubscribing; the publisher just keeps a generic collection of registered listeners.

When the publisher's state changes, it walks that list and calls the same notification method on every entry, without caring what each subscriber actually does with the news - update a display, write a log line, trigger a recalculation. New subscriber types can be added at runtime with zero changes to the publisher, because the publisher only ever depends on a small notification interface, not on any concrete consumer.

When to Use

  • Reach for Observer when one object's state change needs to ripple out to a set of other objects that isn't fixed or fully known in advance.
  • Use it when interested parties need to come and go dynamically - watching only during a specific screen, session, or operation.

Real-World Examples

  • **DOM events** - `element.addEventListener('click', handler)` subscribes a handler to notifications the element publishes.
  • **RxJS Observables** - a stream publisher notifies every subscribed operator chain each time a new value is emitted.
  • **Spreadsheet formulas** - changing one cell automatically recalculates and re-renders every cell whose formula references it.