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.
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.
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();from typing import Callable
Listener = Callable[[str, float], None]
class StockTicker:
def __init__(self):
self._listeners: list[Listener] = []
def subscribe(self, fn: Listener) -> Callable[[], None]:
self._listeners.append(fn)
return lambda: self._listeners.remove(fn)
def publish(self, symbol: str, price: float):
for fn in list(self._listeners): # copy: listeners may unsubscribe while iterating
try:
fn(symbol, price)
except Exception:
logger.exception("listener failed")
ticker = StockTicker()
unsubscribe = ticker.subscribe(lambda s, p: chart.plot(s, p))
ticker.publish("ACME", 98.5)
unsubscribe()type Listener<T> = (event: T) => void;
class Subject<T> {
private listeners = new Set<Listener<T>>();
subscribe(fn: Listener<T>): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn); // unsubscribe function
}
emit(event: T) {
for (const fn of [...this.listeners]) {
try { fn(event); } catch (e) { console.error("listener failed", e); }
}
}
}
const prices = new Subject<{ symbol: string; price: number }>();
const off = prices.subscribe(({ symbol, price }) => chart.plot(symbol, price));
prices.emit({ symbol: "ACME", price: 98.5 });
off();Push vs pull
| Model | Subject sends | Pros | Cons |
|---|---|---|---|
| Push | The changed data (onPrice(symbol, price)) | Observers have what they need | Subject must guess what observers want |
| Pull | Just "I changed" (onChange(subject)) | Observers fetch exactly what they need | Extra 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
- Subject holds direct references to observers
- Usually synchronous, in-process
- Observers know the subject they subscribe to
- 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.
useEffect(() => {
const off = prices.subscribe((e) => setPrice(e.price));
return off; // cleanup runs on unmount: no leak
}, []);# Context manager to guarantee unsubscription
from contextlib import contextmanager
@contextmanager
def subscribed(subject, fn):
off = subject.subscribe(fn)
try:
yield
finally:
off()// AutoCloseable subscription for try-with-resources
try (var sub = ticker.subscribeCloseable(this::onPrice)) {
runSession();
} // unsubscribed automatically- 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.
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.