Observer
Let objects subscribe to another object's changes, so it can notify all of them without knowing who they are.
Description
Observer splits a subject, the thing that changes, from its observers, the things that care. Observers register with the subject; when something happens, the subject calls each of them through one small interface.
The subject never imports the email sender, the stock system or the metrics code. You add a reaction by subscribing a new observer, not by editing the subject. DOM events, EventEmitter and reactive UI state are all Observer under the hood.
Class diagram
Observer pattern class diagram
- Class OrderStore with + subscribe(o): Unsubscribe, + place(event): void.
- Interface OrderObserver with + onOrderPlaced(event): void.
- Class ConfirmationEmail with + onOrderPlaced(event).
- Class StockReservation with + onOrderPlaced(event).
- Class SalesMetrics with + onOrderPlaced(event).
- OrderStore notifies 0..* OrderObserver.
- ConfirmationEmail implements OrderObserver.
- StockReservation implements OrderObserver.
- SalesMetrics implements OrderObserver.
Sequence diagram
Observer pattern sequence diagram
- App → OrderStore: subscribe(email).
- App → OrderStore: subscribe(stock).
- App → OrderStore: place(order).
- OrderStore → ConfirmationEmail: onOrderPlaced(event).
- OrderStore → StockReservation: onOrderPlaced(event).
- App receives "done" back from OrderStore.
TypeScript example
An order store that tells an email sender, a stock system and a metrics counter about every new order, without knowing any of them.
// Observer: an order store notifies whoever is interested when an order is placed.
interface OrderPlaced {
orderId: string;
email: string;
items: { sku: string; qty: number }[];
}
// The observer interface.
interface OrderObserver {
onOrderPlaced(event: OrderPlaced): void;
}
// The subject keeps a list of observers and knows nothing else about them.
class OrderStore {
private readonly observers = new Set<OrderObserver>();
subscribe(observer: OrderObserver): () => void {
this.observers.add(observer);
return () => this.observers.delete(observer); // unsubscribe handle
}
place(event: OrderPlaced): void {
// ...save the order, then tell everyone
for (const observer of this.observers) {
try {
observer.onOrderPlaced(event);
} catch (err) {
// one failing observer must not stop the others
console.error("observer failed", err);
}
}
}
}
// Concrete observers: each reacts in its own way.
class ConfirmationEmail implements OrderObserver {
readonly sent: string[] = [];
onOrderPlaced(e: OrderPlaced): void {
this.sent.push(`To ${e.email}: order ${e.orderId} confirmed`);
}
}
class StockReservation implements OrderObserver {
readonly reserved = new Map<string, number>();
onOrderPlaced(e: OrderPlaced): void {
for (const { sku, qty } of e.items) this.reserved.set(sku, (this.reserved.get(sku) ?? 0) + qty);
}
}
class SalesMetrics implements OrderObserver {
orders = 0;
onOrderPlaced(): void {
this.orders += 1;
}
}
export function demo(): string[] {
const store = new OrderStore();
const email = new ConfirmationEmail();
const stock = new StockReservation();
const metrics = new SalesMetrics();
store.subscribe(email);
store.subscribe(stock);
const stopMetrics = store.subscribe(metrics);
store.place({ orderId: "A-100", email: "sam@example.com", items: [{ sku: "mug", qty: 2 }] });
stopMetrics(); // metrics no longer listens
store.place({ orderId: "A-101", email: "kim@example.com", items: [{ sku: "mug", qty: 1 }] });
return [...email.sent, `mugs reserved: ${stock.reserved.get("mug")}`, `orders counted: ${metrics.orders}`];
}When to use it
Use it when
- Several independent parts of the code must react when one thing changes or happens.
- The set of reactions changes over time, or differs per configuration or plugin.
- You want the source of an event to stay ignorant of what its listeners do.
- UI state must stay in sync with a model without the model knowing about the UI.
Avoid it when
- There is exactly one reaction that will always happen. Call it directly; it's easier to follow.
- The order of reactions matters or one depends on another's result. Make the sequence explicit instead.
- Listeners live in other services or must survive crashes. Use a message broker (the cloud Publisher–Subscriber pattern), not in-process observers.
Pitfalls
- Forgotten subscriptions keep observers alive and leak memory. Always return and use an unsubscribe handle.
- A slow or throwing observer can block or break the others. Isolate failures, and move heavy work off the notification path.
- Cascades are hard to debug: an observer changes state, which notifies other observers, and so on. Keep notifications one level deep.
- Observers that need lots of data pull it back from the subject, creating tight coupling. Send a self-contained event instead.
Alternatives
Publisher–Subscriber
Choose it when subscribers run in other processes or services and messages must be durable.
Mediator
Choose it when many objects talk to each other in many directions and you want one place that coordinates them.
Direct call
Choose it when there is one fixed reaction. A plain method call is simpler and easier to trace.
Reactive streams (RxJS, signals)
Choose it when you need to combine, filter or debounce streams of changes over time.