Start with the real-world problem
A shop places an order. An email receipt, a warehouse notification, and an analytics update all need to react. If the order function directly calls every subsystem, adding a new reaction means reopening that function each time.
Before the pattern
The order service knows how to email, update a dashboard, and notify a warehouse. Optional features become hard dependencies, and removing a consumer requires editing the publisher.
What Observer changes
Let consumers subscribe to a publisher. After the order is placed, the publisher sends one event to its current listeners. The publisher knows the event contract, not the business details of each reaction.
Subject
OrderEvents
Stores listeners and publishes a snapshot to the current subscribers.
Event
OrderPlaced
Carries the order ID and total, without exposing a mutable order object.
Observers
Receipt · Warehouse · Analytics
Register their own reactions and receive an unsubscribe function.
- 01
Publish a fact
OrderPlaced describes something that has happened. In this example the order ID and total are primitive values; freezing a copied event prevents a listener from changing those values for the next listener.
- 02
Manage the subscription lifetime
subscribe returns an unsubscribe function. The demo uses it when a reaction is disabled and when the component unmounts. Without cleanup, repeated subscriptions can duplicate work and retain references.
- 03
Choose failure semantics deliberately
This publisher calls listeners synchronously in registration order. It catches each synchronous exception, records it, and continues. Disable Receipt or make Analytics fail in the demo, then place another order to see which reactions ran.
Try it in the workbench
Live · runs in your browserResult
Place an order to notify the subscribers.
Latest 12 deliveries. In-memory simulation; no messages are sent.
The complete implementation
Download this self-contained example. With Node.js installed, run npx tsx observer.ts in the download directory. The first run may install the TypeScript runner. No API credentials or other project files are needed.
export type OrderPlaced = Readonly<{ orderId: string; totalCents: number }>
export type OrderListener = (event: OrderPlaced) => void
// An in-process, synchronous example. No queue or delivery guarantees.
export class OrderEvents {
private listeners = new Set<OrderListener>()
subscribe(listener: OrderListener) {
this.listeners.add(listener)
return () => { this.listeners.delete(listener) }
}
publish(event: OrderPlaced) {
const snapshot = Object.freeze({ ...event })
const errors: string[] = []
let delivered = 0
for (const listener of [...this.listeners]) {
try {
listener(snapshot)
delivered += 1
} catch (error) {
errors.push(error instanceof Error ? error.message : String(error))
}
}
return { delivered, errors }
}
}
// Run this example with: npx tsx observer.ts
const events = new OrderEvents()
const stopReceipt = events.subscribe(event => console.log(`Receipt: ${event.orderId}`))
events.subscribe(event => console.log(`Warehouse: ${event.orderId}`))
events.publish({ orderId: 'ORD-1001', totalCents: 3500 })
stopReceipt()
events.publish({ orderId: 'ORD-1002', totalCents: 3500 })
Expected terminal output
Receipt: ORD-1001 Warehouse: ORD-1001 Warehouse: ORD-1002
Make the tradeoff deliberately
A good fit
- Several independent in-process consumers react to the same event.
- Subscribers need to join or leave without modifying the publisher.
Keep it simpler when
- One explicit function call makes the dependency easier to understand.
- You need durable delivery across processes; this in-memory publisher cannot provide it.
Taking this into a real system
This is a synchronous teaching example, not a message broker. Async listeners need an explicit awaited error policy; the catch here does not handle a later Promise rejection. An app restart loses in-memory events. For reliable external actions, evaluate an outbox or queue, retries, idempotent consumers, observability, and what happens when one consumer fails. Slow synchronous listeners also delay the publisher.
Your turn
Make one small extension
Unsubscribe the receipt listener after the first order. Publish a second order. Which consumers should receive the second event?
Show the reasoning
Only the listeners that remain subscribed. In the downloadable example, Warehouse receives ORD-1002 while Receipt does not. Calling the returned unsubscribe function repeatedly is harmless because Set.delete is safe when the listener is absent.
Further reading
Examples are original teaching implementations. Reference links provide language and API context; they are not claims that a provider uses this exact implementation.