Observer

One-to-many notification when state changes — subjects and observers, push vs pull, event emitters, pub/sub, reactive streams, memory leaks from forgotten subscriptions, and thread-safety concerns.

Intermediate 2 min readLesson 15 of 24 Interview Q&A

Intent: define a one-to-many dependency so that when one object (the subject) changes state, all its dependents (observers) are notified automatically.

It decouples the thing that changes from the things that react: the subject only knows it has a list of observers implementing an interface — not who they are or what they do.

update(price)StockTicker (subject)subscribe · unsubscribe · notifyPriceChartAlertServiceAuditLog

Implementation

interface PriceListener { void onPrice(String symbol, double price); }

class StockTicker {
    // CopyOnWriteArrayList: safe if listeners subscribe/unsubscribe during notification
    private final List<PriceListener> listeners = new CopyOnWriteArrayList<>();

    public Runnable subscribe(PriceListener l) {
        listeners.add(l);
        return () -> listeners.remove(l);            // handle for unsubscribing
    }

    public void publish(String symbol, double price) {
        for (PriceListener l : listeners) {
            try {
                l.onPrice(symbol, price);
            } catch (RuntimeException e) {
                log.warn("listener failed", e);      // one bad observer must not break the rest
            }
        }
    }
}

StockTicker ticker = new StockTicker();
Runnable unsubscribe = ticker.subscribe((s, p) -> chart.plot(s, p));
ticker.subscribe((s, p) -> { if (p < 100) alerts.send(s + " below 100"); });
ticker.publish("ACME", 98.5);
unsubscribe.run();

Push vs pull

ModelSubject sendsProsCons
PushThe changed data (onPrice(symbol, price))Observers have what they needSubject must guess what observers want
PullJust "I changed" (onChange(subject))Observers fetch exactly what they needExtra calls; data may change again before the pull

Where you've seen it

  • DOM events: button.addEventListener("click", handler).
  • Node.js EventEmitter: stream.on("data", ...).
  • UI frameworks: MVC (views observe models), React state subscriptions, Vue/MobX reactivity, Android LiveData.
  • Java: PropertyChangeListener, Swing listeners, Flow.Subscriber.
  • Reactive programming: RxJS/Reactor/RxJava Observable — observers plus operators (map, filter, debounce) and backpressure.
  • Webhooks and pub/sub systems at the distributed level.

Observer vs Pub/Sub

Observer
  • Subject holds direct references to observers
  • Usually synchronous, in-process
  • Observers know the subject they subscribe to
Publish / subscribe
  • A broker/event bus sits between publishers and subscribers
  • Neither side knows the other — only topic names
  • Often asynchronous, possibly across processes (Message queues)

Pitfalls

  • Unexpected cascades: an observer's reaction changes state that notifies more observers… Hard to trace and can loop.
  • Order of notification is usually undefined; don't rely on it.
  • Exceptions: isolate observers so one failure doesn't stop the rest.
  • Threading: notifications run on the publisher's thread; slow observers block the publisher. Hand off to an executor or queue for heavy work. Iterate over a snapshot (or a copy-on-write list) so concurrent subscribe/unsubscribe is safe.
  • Debugging: control flow is implicit — "who reacts to this event?" requires searching the code.
Cleaning up in React
useEffect(() => {
  const off = prices.subscribe((e) => setPrice(e.price));
  return off;                        // cleanup runs on unmount: no leak
}, []);
Key takeaways
  • Observer notifies many dependents when a subject changes, keeping them decoupled.
  • Return an unsubscribe handle; always unsubscribe to avoid memory leaks.
  • Isolate observer failures; beware cascades and slow observers on the publisher's thread.
  • Pub/sub adds a broker so publishers and subscribers don't know each other.
  • Event emitters, DOM events, reactive streams and UI state are all observers.
Interview questions
QHow can the observer pattern cause memory leaks?medium

The subject keeps strong references to its observers. If an observer that should be short-lived never unsubscribes, it stays reachable from the long-lived subject and cannot be garbage collected, along with everything it references. Fix it by unsubscribing in lifecycle cleanup, using scoped subscription handles, or weak references.