Skip to content

Observer Pattern: Notify Subscribers Without Coupling to Them

Learn the Observer pattern through a bike-share dock example, including subscribe and unsubscribe, event payloads and listener memory leaks.

13 min readDesign patternBehavioural

Define a one-to-many dependency so that when one object (the subject) changes state, all its registered dependents (observers) are notified automatically, without the subject depending on their concrete classes.

Observer lets one object announce that its state changed, while any number of other objects decide for themselves what to do about it. The announcing object keeps a list of subscribers and calls each one. It never needs to know what they are. You already use it every time you write addEventListener, connect a signal, or register a callback. Interviewers like it because it looks trivial and isn't. Expect follow-up questions on notification order, what happens when a listener throws, synchronous versus asynchronous delivery, and the classic leak: a subscriber that is never removed stays alive as long as the subject does. This guide builds one example from start to finish: a bike-share docking station that has to keep a rider map, a van dispatcher and an analytics log in sync.

The problem

A situation where the obvious design starts to hurt.

You work on Harbor Bikes, a bike-share network with 340 docking stations across a coastal city. Each station has a fixed number of docks, and the count of available bikes changes every time a rider undocks or returns a bike. The pier-7 station has 12 docks and is one of the busiest.

Three parts of the system care about those changes. The rider app shows a live map screen with bike and free-dock counts. The operations team runs a rebalancing dispatcher that sends a van when a station has 2 or fewer bikes, or 2 or fewer free docks. The data team logs every change for demand forecasting.

The first version wired this directly. DockStation.undockBike() called mapScreen.refresh(), then dispatcher.check(), then logger.record(). Every new consumer meant editing DockStation. When marketing asked for a push notification to riders who favourited a station, the change touched the station class again, and its test suite had to construct fake map screens, fake vans and fake loggers just to test a counter.

The second problem showed up in production. Map screens are created every time a rider opens the app and destroyed when they leave. Someone added a list of screens to the station so it could refresh them, but nothing ever removed a screen from that list. After a day of traffic, a busy station held references to thousands of closed screens, each still being redrawn off-screen on every change, and the app's memory kept climbing until the operating system killed it.

The solution

What the pattern proposes.

Turn the station into a subject that knows only one thing about its consumers: they implement a small StationListener interface with a single method, onAvailabilityChanged(event). The station keeps a collection of listeners, exposes subscribe to add one, and calls every listener after each state change.

The station builds an immutable AvailabilityEvent containing the station id, bike count and free-dock count, and passes it to each listener. This is the push model: listeners get the data they need without reaching back into the station. The map screen redraws, the dispatcher compares the counts with its threshold, and the logger appends the event. Adding a push-notification feature becomes a new class plus one subscribe call. DockStation does not change.

To fix the leak, subscribe returns an unsubscribe function. Whoever subscribes owns that handle and must call it when the listener's lifetime ends, for example when a map screen closes. Making removal a value returned from registration puts the cleanup right next to the setup, where reviewers can see it.

Two details make the implementation robust. The station iterates over a snapshot of its listeners, so a listener that unsubscribes during a notification does not corrupt the loop. And it uses an insertion-ordered set, so subscribing the same object twice does not cause duplicate notifications.

An everyday analogy

The same idea, outside software.

Picture the coach of a youth football club on a rainy Saturday morning. She keeps a call list of parents. When the pitch is waterlogged and the match is cancelled, she goes down the list and rings everyone with the same message: match off, pitch closed. What each family does next is up to them. One goes back to bed, one books a swimming lesson, one tells grandparents not to drive over. The coach does not need to know any of that.

Parents join the list when their child signs up, and they are supposed to ask to be removed when the child leaves the club. If they forget, the coach keeps calling numbers that no longer care, and the list grows every season. That forgotten removal is exactly the listener leak you will be asked about in interviews.

Structure

The pieces and how they relate.

DockStation notifies any StationListener through one interface; subscribers keep the returned unsubscribe handle.App bootstrap calls DockStation (subscribe(listener)). DockStation has a StationListener (0..* listeners). DockStation creates AvailabilityEvent (on each change). RiderMapScreen implements StationListener. RebalancingDispatcher implements StationListener. UsageLogger implements StationListener.App bootstrapwires subscriptionsDockStationsubscribe(),dockBike()…«interface»StationListeneronAvailabilityChanged(event)AvailabilityEventstationId, bikes,freeDocksRiderMapScreenredraws countsRebalancingDispatchersends a van atthresholdUsageLoggerrecords every changeUnsubscribe oncloseotherwise thestation keeps th…subscribe(listener)0..* listenerson each change
DockStation notifies any StationListener through one interface; subscribers keep the returned unsubscribe handle.

Participants

Subject (DockStation)
Owns the state that changes. Keeps a collection of listeners, offers subscribe and returns an unsubscribe handle, and notifies every listener after each state change. Depends only on the StationListener interface.
Observer interface (StationListener)
The single method every subscriber implements, onAvailabilityChanged(event). It is the whole contract between the station and its consumers.
Event (AvailabilityEvent)
An immutable snapshot of what changed: station id, bikes and free docks. Pushing it to listeners means they never need to query the station back mid-notification.
Concrete observers (RiderMapScreen, RebalancingDispatcher, UsageLogger)
Each reacts to the event in its own way: redraw, dispatch a van, or record. They can be added or removed without touching the station.
Client (App bootstrap)
Creates the station and the listeners, wires subscriptions, and holds the unsubscribe handles so it can release short-lived listeners such as screens.

Pseudocode

The solution to the scenario, language-neutral.

interface StationListener
    method onAvailabilityChanged(event)

class DockStation
    field id, capacity, bikes
    field listeners = empty ordered set

    method subscribe(listener)
        listeners.add(listener)
        return function unsubscribe()
            listeners.remove(listener)

    method undockBike()
        if bikes == 0 then fail "station empty"
        bikes = bikes - 1
        notify()

    method dockBike()
        if bikes == capacity then fail "station full"
        bikes = bikes + 1
        notify()

    private method notify()
        event = AvailabilityEvent(id, bikes, capacity - bikes)
        for each listener in copy(listeners)
            listener.onAvailabilityChanged(event)

class RebalancingDispatcher implements StationListener
    field threshold
    method onAvailabilityChanged(event)
        if event.bikes <= threshold then send van to deliver bikes
        else if event.freeDocks <= threshold then send van to collect bikes

// wiring
station = DockStation("pier-7", capacity 12, bikes 3)
station.subscribe(RebalancingDispatcher(2))
station.subscribe(UsageLogger())
closeScreen = station.subscribe(RiderMapScreen("map-screen-1"))
station.undockBike()      // all three react
closeScreen()             // screen closed: release it
station.dockBike()        // only dispatcher and logger react

The code

The same solution in TypeScript, Python and PHP.

interface AvailabilityEvent {
  readonly stationId: string;
  readonly bikes: number;
  readonly freeDocks: number;
}

interface StationListener {
  onAvailabilityChanged(event: AvailabilityEvent): void;
}

class DockStation {
  private readonly listeners = new Set<StationListener>();
  private bikes: number;

  constructor(readonly id: string, readonly capacity: number, bikes: number) {
    this.bikes = bikes;
  }

  subscribe(listener: StationListener): () => void {
    this.listeners.add(listener);
    return () => {
      this.listeners.delete(listener);
    };
  }

  listenerCount(): number {
    return this.listeners.size;
  }

  undockBike(): void {
    if (this.bikes === 0) throw new Error(`${this.id} is empty`);
    this.bikes--;
    this.notify();
  }

  dockBike(): void {
    if (this.bikes === this.capacity) throw new Error(`${this.id} is full`);
    this.bikes++;
    this.notify();
  }

  private notify(): void {
    const event: AvailabilityEvent = {
      stationId: this.id,
      bikes: this.bikes,
      freeDocks: this.capacity - this.bikes,
    };
    for (const listener of [...this.listeners]) {
      listener.onAvailabilityChanged(event);
    }
  }
}

class RiderMapScreen implements StationListener {
  constructor(private readonly name: string) {}

  onAvailabilityChanged(e: AvailabilityEvent): void {
    console.log(`[${this.name}] ${e.stationId}: ${e.bikes} bikes, ${e.freeDocks} free docks`);
  }
}

class RebalancingDispatcher implements StationListener {
  constructor(private readonly threshold: number) {}

  onAvailabilityChanged(e: AvailabilityEvent): void {
    if (e.bikes <= this.threshold) {
      console.log(`Dispatch van: bring bikes to ${e.stationId}`);
    } else if (e.freeDocks <= this.threshold) {
      console.log(`Dispatch van: collect bikes from ${e.stationId}`);
    }
  }
}

class UsageLogger implements StationListener {
  readonly events: AvailabilityEvent[] = [];

  onAvailabilityChanged(e: AvailabilityEvent): void {
    this.events.push(e);
  }
}

const station = new DockStation("pier-7", 12, 3);
const logger = new UsageLogger();
station.subscribe(new RebalancingDispatcher(2));
station.subscribe(logger);

const closeScreen = station.subscribe(new RiderMapScreen("map-screen-1"));

station.undockBike();
// Dispatch van: bring bikes to pier-7
// [map-screen-1] pier-7: 2 bikes, 10 free docks

closeScreen(); // the rider left the screen: release it or it leaks

station.dockBike(); // 3 bikes, 9 free docks: only the logger records it

console.log(`listeners: ${station.listenerCount()}, logged events: ${logger.events.length}`);
// listeners: 2, logged events: 2

When to use it

Situations where it pays off.

  • Several parts of the system must react when one object changes, and the set of reacting parts grows or varies over time.

    The subject loops over an interface instead of calling named collaborators, so new reactions are new classes rather than edits to the subject. That keeps the subject stable and testable on its own.

  • Consumers come and go at runtime, such as UI screens, websocket connections or temporary monitors.

    Subscribe and unsubscribe are runtime operations. A list of hard-coded calls cannot express a screen that exists for 40 seconds and then disappears.

  • A lower-level module must inform a higher-level one without importing it.

    The station lives in the domain layer and has no idea that a mobile map or a van-dispatch service exists. Observer inverts the dependency: the outer layers depend on the station's listener interface, not the other way round.

  • You want to cut a growing method that ends in a string of side-effect calls to unrelated components.

    Replacing those calls with one notify step separates the core state change from its consequences, which is easier to read, review and test.

How to implement it

Steps to introduce it in existing code.

  1. Identify the subject: the object whose state changes and the exact moments that count as a change. For the station, that is after dockBike and undockBike succeed.

  2. Define a small observer interface with one method per kind of event. Keep it narrow; a listener should not have to implement methods it ignores.

  3. Decide on push or pull. Pushing an immutable event object is usually safer than handing out the subject, because listeners cannot mutate it or read half-updated state.

  4. Give the subject a collection of listeners plus a subscribe method that returns an unsubscribe handle. Use an ordered set so double subscription is harmless and order is predictable.

  5. Notify after the state is fully updated, iterating over a copy of the collection so listeners can unsubscribe themselves during delivery.

  6. Move each former direct call into its own observer class and register it during application wiring.

  7. For every short-lived subscriber, store the unsubscribe handle in the object that owns its lifetime and call it in the teardown path: screen close, component unmount, connection drop.

  8. Decide and document failure behaviour: whether one listener's exception stops the others, and whether delivery is synchronous or queued.

Pros and cons

What you gain and what you pay.

Pros

  • Open/Closed in practice: new reactions to a station change are new classes, and DockStation stays untouched.
  • The subject depends only on a tiny interface, so it can be unit tested with a single recording listener.
  • Subscriptions are dynamic, which fits UI screens and connections that appear and disappear at runtime.
  • Each observer has one job, which keeps the redraw, dispatch and logging logic in separate, focused classes.

Cons

  • Forgotten unsubscriptions leak memory: the subject's collection keeps every registered listener reachable, along with everything that listener references.
  • Control flow becomes implicit. Reading undockBike no longer tells you what happens next, so debugging means finding every subscriber.
  • Synchronous notification means one slow or throwing listener delays or breaks the rest and the caller.
  • Cascades are easy to create by accident: a listener that changes another subject can trigger long or even circular notification chains.
  • Depending on notification order between listeners is fragile, yet tempting once there are many of them.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Why does Observer cause memory leaks, and how do you prevent them?

The subject's listener collection holds a strong reference to every subscriber. As long as the subject is reachable, so is each listener and everything it references, such as a whole screen and its views. In the example, a long-lived pier-7 station would keep every closed map screen alive. Prevent it by returning an unsubscribe handle from subscribe and calling it in the owner's teardown path, or by tying subscriptions to a lifecycle object that releases them all at once, such as an AbortSignal in the browser or a disposable bag in a component.

Should I use weak references for listeners instead?

Sometimes, but not as the default. Weak references (WeakRef in JavaScript, weakref.WeakMethod in Python, WeakReference in PHP) stop the subject from keeping listeners alive, but they also mean a listener may silently vanish once nothing else holds it, and when that happens depends on the garbage collector. Anonymous callbacks are especially prone to disappearing immediately. Explicit unsubscription is predictable and testable. Use weak references only when ownership truly cannot be expressed, and document it.

What happens if one listener throws during notification?

In the plain synchronous loop shown here, the exception propagates out of notify, the remaining listeners are skipped, and the caller of undockBike sees the error even though the bike count already changed. If listeners are independent, catch per listener, report the error, and continue. Whatever you choose, decide it deliberately; interviewers often ask exactly this.

How is Observer different from publish-subscribe?

In classic Observer the subscriber registers directly with the subject and is called in-process, usually synchronously. Publish-subscribe puts a broker or event bus between them: publishers emit to a topic, subscribers listen to the topic, and neither knows the other exists. Pub-sub adds decoupling, and often asynchronous or cross-process delivery, at the cost of another moving part and weaker guarantees about ordering and delivery.

Can listeners rely on being notified in a particular order?

They should not. The examples use insertion-ordered collections, so order is deterministic, which helps tests and debugging. But if the dispatcher only works correctly after the logger has run, you have a hidden dependency between observers. Either merge them, or have one explicitly trigger the other.

Push or pull: should the event carry the data or should listeners query the subject?

Push an immutable event when listeners need a known, small set of facts, as with bikes and free docks here. It avoids listeners reading the subject in a half-updated state and keeps them from calling mutating methods mid-notification. Pull, passing the subject itself, suits cases where listeners need very different data and building a full event each time would be wasteful.

Next guide7 of 10 · Behavioral patternsState Pattern: Explicit State Machines Without the Switch StatementsRead the next one