BehavioralTypeScriptverifiedVerified

Observer Pattern in TypeScript

Defines a one-to-many dependency so that when one object changes state, all its dependents are notified and updated automatically.

How to Implement the Observer Pattern in TypeScript

1Step 1: Define the event listener type

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

2Step 2: Create the EventEmitter class with subscribe/unsubscribe

class EventEmitter<T> {
  private listeners: Listener<T>[] = [];

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

  unsubscribe(listener: Listener<T>): void {
    this.listeners = this.listeners.filter(l => l !== listener);
  }

  emit(event: T): void {
    for (const listener of this.listeners) {
      listener(event);
    }
  }
}

3Step 3: Define the event data interface

// Usage
interface StockUpdate {
  symbol: string;
  price: number;
}

4Step 4: Wire up and test the notification flow

const stockFeed = new EventEmitter<StockUpdate>();

const unsubscribe = stockFeed.subscribe(update => {
  console.log(`${update.symbol}: $${update.price}`);
});

stockFeed.emit({ symbol: "AAPL", price: 182.5 });
stockFeed.emit({ symbol: "GOOG", price: 141.3 });

unsubscribe();

stockFeed.emit({ symbol: "AAPL", price: 183.0 }); // not received

Observer Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Observer Pattern in the Real World

Think of a newspaper subscription service. The publisher (subject) doesn't know exactly who its subscribers (observers) are—it just maintains a list. When a new edition is printed, it delivers a copy to every subscriber on the list automatically. Subscribers can cancel at any time without the publisher needing to change anything.