Skip to content
Velloreth
Programming 6 min read

The Observer Pattern Explained: Events and Subscriptions

The observer pattern lets objects subscribe to changes in another object. Learn how it works, how to avoid leaks, and where it appears in real code.

By

What the observer pattern does

The observer pattern lets one object notify many others when something changes, without knowing who they are.

The publisher maintains a list of subscribers. When its state changes, it iterates the list and notifies each one. Subscribers register and unregister themselves.

type Listener<T> = (value: T) => void;

class Observable<T> {
  private listeners = new Set<Listener<T>>();

  subscribe(listener: Listener<T>): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener); // unsubscribe
  }

  private notify(value: T): void {
    for (const listener of this.listeners) listener(value);
  }
}

Three things define the pattern:

  1. A way to subscribe.
  2. A way to unsubscribe.
  3. A way to notify all subscribers.

A complete example

class Store<T> {
  private state: T;
  private listeners = new Set<Listener<T>>();

  constructor(initial: T) {
    this.state = initial;
  }

  get(): T {
    return this.state;
  }

  set(next: T): void {
    this.state = next;
    for (const listener of this.listeners) listener(next);
  }

  subscribe(listener: Listener<T>): () => void {
    this.listeners.add(listener);
    listener(this.state); // emit current value immediately
    return () => this.listeners.delete(listener);
  }
}

const store = new Store({ count: 0 });

const unsubscribe = store.subscribe((state) => {
  console.log('count is', state.count);
});

store.set({ count: 1 }); // logs: count is 1
unsubscribe();
store.set({ count: 2 }); // no log

Two details are worth noting.

The Set prevents duplicate subscriptions. If the same listener subscribes twice, it is stored once. With an array, it would be called twice.

The immediate emit on subscribe is a design choice. It means subscribers do not need to read the current value separately. Some implementations do this; others do not. Be consistent.

The unsubscribe function

The most important practical detail is that subscribe returns an unsubscribe function.

const unsubscribe = store.subscribe(handler);

// later, when the handler is no longer needed
unsubscribe();

Without this, the publisher holds a reference to the subscriber forever. In a long-running application, that is a memory leak.

The leak is especially common in single-page applications. A component subscribes on mount, the user navigates away, the component is destroyed — but the subscription remains, holding the component and its data alive.

// React example
useEffect(() => {
  const unsubscribe = store.subscribe(setState);
  return unsubscribe; // cleanup on unmount
}, []);

The cleanup function is what prevents the leak. Forgetting it is the single most common observer bug.

Where the pattern appears

DOM events. addEventListener and removeEventListener are the observer pattern.

button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);

Reactive frameworks. Vue’s reactivity, Svelte’s stores, and RxJS observables are all observer-based.

Message buses. An event bus lets unrelated parts of an application communicate.

bus.on('user:created', (user) => sendWelcomeEmail(user));
bus.on('user:created', (user) => createDefaultSettings(user));

WebSocket handlers. Each message type can have its own subscribers.

State management. Redux’s subscribe, MobX’s autorun, and Zustand’s subscribe all follow the pattern.

Node’s EventEmitter. The standard library’s event system.

File watchers and streams. fs.watch and stream events notify on change.

Observer vs pub-sub

The two are often conflated. The difference is the broker.

Observer: subscribers register directly with the publisher. The publisher knows its subscribers.

Publisher → Subscriber A
          → Subscriber B

Pub-sub: publishers and subscribers communicate through a broker. Neither knows the other.

Publisher → Broker → Subscriber A
                   → Subscriber B

Pub-sub is more decoupled — a publisher can be replaced without touching subscribers — but it is harder to trace, because the connection is indirect. It also needs a broker, which is infrastructure.

Use observer when the relationship is direct and local. Use pub-sub when components should not know about each other at all.

Hot vs cold observables

A distinction that matters in reactive libraries.

Hot observables emit regardless of subscribers. A DOM event fires whether or not anyone is listening; a subscriber that joins late misses earlier events.

Cold observables start producing when subscribed. An HTTP request wrapped in an observable does not fire until someone subscribes, and each subscriber may trigger a separate request.

The distinction determines when work happens and whether late subscribers miss data. It is a common source of confusion in RxJS.

The downsides

Control flow is hard to trace. When a publisher notifies, the code that runs is not visible at the call site. Debugging means finding who subscribed.

store.set(newState); // what runs? unknown from here

Order is not guaranteed. With a Set, insertion order is preserved in JavaScript, but relying on it is fragile. Subscribers should not depend on each other’s execution order.

Errors propagate. If one listener throws, the loop stops and later listeners are not called. Wrap each call in a try/catch if that matters.

for (const listener of this.listeners) {
  try {
    listener(value);
  } catch (error) {
    console.error('Listener failed:', error);
  }
}

Leaks. As discussed, forgetting to unsubscribe retains memory.

Cascading updates. A listener that triggers another update can cause a cascade, or an infinite loop if the updates feed back.

When to use it

Use observers when:

  • One change must notify several independent consumers.
  • The publisher should not know its consumers.
  • Consumers come and go at runtime.
  • You are building a reactive data layer.

Do not use observers when:

  • There is exactly one consumer — use a callback or a promise.
  • The flow is sequential — use direct calls.
  • You need a return value — observers are fire-and-forget.
  • The relationship is simple and static — direct calls are clearer.

The last point is the most important. Observers add indirection, and indirection has a cost. Use them where the decoupling is genuinely needed.

Practical guidance

  • Always return and use the unsubscribe function.
  • Use a Set to prevent duplicate subscriptions.
  • Wrap listener calls in try/catch so one failure does not stop the rest.
  • Emit the current value on subscribe if subscribers need it, and document the choice.
  • Do not rely on listener order.
  • Prefer a callback for a single consumer.
  • Clean up in the framework’s unmount hook to avoid leaks.
  • Consider whether pub-sub is needed — direct observer is simpler when it suffices.

For the related patterns, see design patterns for beginners and factory pattern explained. For the async context, event loop explained and callbacks explained.

Quotable summary

The observer pattern lets one object notify many subscribers when its state changes, without knowing who they are, through subscribe, unsubscribe, and notify. The unsubscribe function is essential, because the publisher holds a reference to every subscriber and forgetting to unsubscribe leaks memory — the most common observer bug in single-page applications. Observers decouple the publisher from its consumers, which is powerful but makes control flow harder to trace, since the code that runs on notification is not visible at the call site. The pattern underlies DOM events, reactive frameworks, message buses, and WebSocket handlers. Prefer a callback or promise when there is exactly one consumer; observers are for genuine one-to-many notification.

Frequently asked questions

What is the observer pattern in simple terms?
The observer pattern lets objects sign up to be notified when something changes. The object that changes does not need to know who is listening; it just announces the change and everyone who subscribed hears about it.
What is the difference between the observer pattern and pub-sub?
In the observer pattern, subscribers register directly with the publisher. In pub-sub, they communicate through a broker or event bus, so publisher and subscriber do not know each other at all. Pub-sub is more decoupled and more complex.
Why do observers cause memory leaks?
Because the publisher holds a reference to every subscriber. If a subscriber is no longer needed but never unsubscribes, the publisher keeps it alive. This is common in single-page applications where components mount and unmount.
What is the difference between a hot and cold observable?
A hot observable emits regardless of whether anyone is subscribed, like a DOM event. A cold observable starts producing only when subscribed, like an HTTP request wrapped in an observable. The distinction matters for when work begins.
Should I use the observer pattern for everything?
No. Use it when one change must notify several independent consumers. For a single consumer, a callback or a promise is simpler and easier to follow. Observers add indirection that is only worth it for genuine one-to-many notification.
How do I avoid observer leaks?
Always keep the unsubscribe function returned by the subscribe call and invoke it when the subscriber is no longer needed. In component frameworks, do this in the cleanup or unmount hook.