Observer lets one object, the subject, notify any number of other objects, the observers, when something happens to it, without knowing what those objects are. Observers subscribe through a small interface, and the subject simply loops over its subscribers and calls each one. New reactions are added by subscribing a new object, not by editing the subject. It is the idea behind every addEventListener, every on("event", ...), every reactive store and every model-view binding.
Think of it like
A newsletter mailing list
A newsletter does not know its readers personally. Anyone can sign up, and anyone can unsubscribe at the bottom of an email. When a new issue is ready, the publisher sends it to whoever is on the list at that moment, in one go. The publisher never changes when a new reader joins, and a reader who left simply stops getting issues. The newsletter is the subject, the mailing list is its list of observers, the sign-up form is subscribe() and the unsubscribe link is unsubscribe().
The problem
An online shop places orders through an OrderService. When an order goes through, three things must happen: the buyer gets an email receipt, a text message, and the analytics team counts the sale. The direct way is to give OrderService the three services and call each one. This is the Before version in the visualizer above.
class OrderService {
constructor(
private email: EmailService,
private sms: SmsService,
private stats: AnalyticsService,
) {}
placeOrder(id: string): void {
// ...save the order, take payment...
this.email.sendReceipt(id);
this.sms.sendText(id);
this.stats.track();
}
}
const orders = new OrderService(new EmailService(), new SmsService(), new AnalyticsService());
orders.placeOrder("A1"); // email, text and analytics, always all threeIt works, and with three reactions it is easy to read. The cost shows up when the list of reactions starts to move:
- Every new reaction edits
OrderService. A push notification needs a new constructor parameter, a new field and a new call insideplaceOrder(), in the class that every order goes through. It is never closed for modification, which the open/closed principle in SOLID Principles asks for. - It knows every concrete class.
OrderServiceimports the email, SMS and analytics services and calls each through its own method name (sendReceipt,sendText,track). Ordering code now changes when a messaging API changes. - The reactions are fixed at compile time. A buyer who turns off text messages cannot be handled without adding a flag and an
iftoOrderService. Nothing can join or leave while the program runs. - Coarse tests. Testing
placeOrder()means building, or faking, every service it calls. - Dependencies point the wrong way. The core business object depends on the side effects around it. When analytics later needs to call back into orders, you get a dependency cycle.
The pattern
Intent: define a one-to-many dependency between objects so that when one object changes state or does something, all its dependents are notified automatically, without the object knowing who they are.
- Subject
- The object being watched. It keeps a list of observers and offers
subscribe()andunsubscribe()(also called attach/detach,addListener/removeListener,on/off). When something happens, it notifies every observer on the list. - Observer (
OrderListener) - The interface every subscriber implements, usually one method such as
onOrderPlaced(id)(the classic name isupdate()). It is all the subject knows about its subscribers. - Concrete subject (
OrderService) - The real class that holds the state or does the work. Its
listenersfield is a list typed as the interface (an aggregation marked0..*: any number of listeners, none of them owned). After placing an order it loops over that list and callsonOrderPlaced(id)on each, without naming a concrete class, so adding a reaction cannot break it. - Concrete observer (
EmailNotifier,SmsNotifier,AnalyticsTracker) - One class per reaction. Each implements
OrderListenerand does its own job: send an email, send a text, count the sale. - Client
- The code that wires it up: it creates the subject and the observers and decides who subscribes, and later who unsubscribes. Here, the client program at the bottom of the code panel.
What the visualizer shows
Press Play in the visualizer at the top of the page, or step through it with the arrow buttons. It really runs the classes in the code panel and draws what happened. The running line is highlighted in the code, and the caption under the stage explains every step.
- Class diagram: the classes and methods the current step uses light up. Amber is the code running now, sky blue the caller waiting for an answer, green something just created or returned, and violet the interface that declares the method being called. During a notification, watch the aggregation from
OrderServicetoOrderListenerlight up,OrderListenerturn violet, and the implements line of the one listener that is running light up with it. - Objects at runtime:
orders : OrderServicesits in the middle with its fieldlisteners = [...], and an arrow from that field to every subscribed object. Each listener shows what it has received so far (sent = ["A1"],count = 1). The message in flight travels fromordersto one listener at a time, so the fan-out is three short arrows out of the hub. - Sequence of calls: one lifeline per object. One
placeOrder("A1")from the client produces a row ofonOrderPlaced("A1")calls fromorders, one per listener, in the order they subscribed. - Before / With Observer and Add push: the toggle switches between the hard-wired version and the pattern. Add push applies the change request to whichever version is shown: changed classes get a badge in the class diagram (
new class, oredited +2 −0), and the Change request panel beside the code compares what each version had to change. On a phone the three views sit behind a Classes / Objects / Sequence switch.
Walkthrough
- 1
Create the listeners
With With Observer selected, the client creates
email,smsandstats. Each starts empty:sent = [], orcount = 0for the tracker. - 2
Create the subject
new OrderService()createsorderswithlisteners = []. Nobody is listening yet, andordersworks fine that way. - 3
Subscribe three listeners
orders.subscribe(email)pushesemailonto the list. Two more calls make it[email, sms, stats], and in the Objects view an arrow now runs from thelistenersfield to each of them. - 4
Place an order
The client calls
orders.placeOrder("A1"), once.OrderServicedoes not know which classes are listening; it loops overlisteners. - 5
Fan out
orderscallsonOrderPlaced("A1")onemail, the first object in its list. The method is declared byOrderListener, the object is anEmailNotifier, soEmailNotifier.onOrderPlacedruns andemail.sentbecomes["A1"]. Control returns to the loop, which does the same forsmsand thenstats(countbecomes 1): one event, three reactions, in subscription order. - 6
Unsubscribe one listener
The buyer turns off text messages, so the client calls
orders.unsubscribe(sms).orders.listenersbecomes[email, stats], and the arrow fromorderstosmsdisappears. No class was edited. - 7
Place a second order
orders.placeOrder("A2")runs exactly the same loop, but now onlyemailandstatsare called. At the endsms.sentstill holds only"A1", whileemail.sentis["A1", "A2"]andstats.countis 2. - 8
Add push (change request)
With Add push applied, the code gains one class,
PushNotifier, and the client createspushand subscribes it. Order A1 now fans out to four listeners and A2 to three.OrderServiceis the same code as before.
Before and after
Without the pattern
OrderServiceholds every concrete service and calls each by name- Each service has its own method (
sendReceipt,sendText,track) - Adding push edits
OrderService: constructor andplaceOrder() - Who reacts is fixed in code; turning SMS off needs a flag and an
if - Fewer types; the whole flow is visible in one method
With Observer
OrderServiceknows only theOrderListenerinterface- Every listener implements the same
onOrderPlaced(id) - Adding push adds one class and one
subscribe()call - Listeners join and leave at runtime with
subscribe/unsubscribe - The flow is spread out: to see who reacts, look at the wiring code
| Change request: also send a push notification | Before | With Observer |
|---|---|---|
| Existing classes edited | 1 (OrderService) | 0 |
| New classes | 1 (PushService) | 1 (PushNotifier) |
| Lines changed in existing classes | 2 (+2 −0) | 0 |
| Classes touched | 2 | 1 |
Both versions need a new class for push, because sending a push notification is new work. The difference is where the wiring lives. Before, the two extra lines (a private push: PushService constructor parameter and a this.push.sendPush(id) call) go into OrderService itself, which then has to be re-tested. With Observer, OrderService and the other listeners stay untouched, and the only wiring is a subscribe(push) line in the client. Two lines sound cheap for one change; the point is the trend. Every future reaction (fraud check, loyalty points, warehouse pick list) would edit the same central class, while with Observer each lands in a new class. Compare the class diagrams too: before, three associations leave OrderService; with Observer, one aggregation to OrderListener.
Variations
Push vs pull, sync vs async
In the push model the subject sends the details with the notification: onOrderPlaced(id), or a whole event object. Observers get everything in one call, but the interface fixes what data every observer receives, needed or not. In the pull model the subject sends only "I changed" (often passing itself), and each observer asks the subject for exactly what it needs. That keeps the interface tiny, but every observer needs a reference to the subject and makes extra calls, and by the time it reads, the state may have changed again. The visualizer uses push; passing an immutable event object ({ id, total, placedAt }) is the usual middle ground.
In the visualizer, placeOrder() does not return until every listener has finished: a slow SMS gateway slows down checkout, and listeners run on the caller's thread. Asynchronous delivery decouples the two: the subject queues the event and returns, and listeners run later (on a microtask, a thread pool, or a separate process behind a queue). Browser APIs such as MutationObserver work this way, delivering batched change records after the current script. The price is that observers may see the event after other changes have happened, errors no longer reach the subject, and ordering has to be designed rather than assumed.
Event bus, publish/subscribe and typed events
Put a broker between the two sides and you get Publish/Subscribe: publishers send to a named topic or channel, subscribers register with the broker, and neither side holds a reference to the other. In one process this is an event bus; across services it is a message broker such as Kafka or RabbitMQ, covered in Message Queues & Pub/Sub and Event-Driven Architecture, CQRS & Event Sourcing. The decoupling is stronger, and so is the cost: delivery guarantees, retries, duplicates and ordering become your problem.
String event names (on("orderPlaced", ...)) are flexible but a typo subscribes to an event that never fires, silently. Typed events catch that at compile time: one method per event in the observer interface, one event class per event (Java, C#), or a map from event name to payload type (TypeScript, see the second implementation below), so emit("orderPlaced", { id }) without total does not compile.
Removing observers, and the lapsed listener leak
The subject's list holds a reference to every observer, so an observer that subscribes and is then forgotten stays alive, and keeps reacting, for as long as the subject lives. This lapsed listener problem is one of the most common memory leaks in UI code: a component that adds a listener to window or to a store when it mounts and never removes it when it unmounts.
- Pair every subscribe with an unsubscribe. Return an unsubscribe function or a disposable handle from
subscribe(), and call it in the observer's cleanup (React'suseEffectcleanup,componentWillUnmount,dispose(), a destructor). - Tie the subscription to a lifetime.
addEventListener(type, fn, { signal })removes the listener when theAbortControlleris aborted, and{ once: true }removes it after the first event. - Weak references, so the subject does not keep observers alive:
std::weak_ptrin C++ (the first implementation below),WeakReferencein Java,weakref.WeakSetorWeakMethodin Python. Beware that a lambda held only weakly is collected at once and silently stops firing.
Order, re-entrancy and errors
A list notifies in subscription order, as the visualizer shows, but treat that as an accident of the implementation: if analytics must run after email, make that dependency explicit instead of relying on who subscribed first. Re-entrancy is the other trap. A listener may unsubscribe itself, subscribe another, or call back into the subject while the loop is running. Mutating the list being iterated can skip or repeat listeners, so iterate over a snapshot (or, as unsubscribe does here, replace the list instead of mutating it). A listener that changes the subject can also trigger another round of notifications, and in the worst case an endless cycle; notify only on real changes and guard against nested notifications.
In a plain loop, an exception thrown by the second listener skips the third and propagates out of placeOrder(), after the order was already saved. Decide what you want. Browsers report an exception thrown by an event listener and carry on with the next listener; Node's EventEmitter.emit() lets it propagate, so later listeners do not run. A robust subject usually catches per observer, logs or collects the errors, and keeps notifying the rest.
In real code
| Where | Subject | Subscribe / unsubscribe |
|---|---|---|
| Browser DOM | Any EventTarget: elements, window, document | addEventListener(type, fn, { once, signal }) / removeEventListener(type, fn), which needs the same function reference |
| Browser observer APIs | MutationObserver, IntersectionObserver, ResizeObserver | observe(target) / disconnect(); the callback receives batched records asynchronously |
| Node.js | Any EventEmitter (streams, servers, process) | on, once / off (removeListener); emit calls listeners synchronously, in registration order, and warns when one event passes 10 listeners, a common sign of a leak |
| RxJS | Observable, Subject | subscribe(observer) returns a Subscription; subscription.unsubscribe(). Observers have next, error and complete |
| Java | Beans with PropertyChangeSupport; Swing components | addPropertyChangeListener / removePropertyChangeListener, Swing's addActionListener. java.util.Observable and java.util.Observer are deprecated since Java 9 |
| C# / .NET | Any class with an event | button.Click += handler / -= handler; IObservable<T>.Subscribe returns an IDisposable |
| Redux | The store | store.subscribe(listener) returns the unsubscribe function |
| React | External stores | useSyncExternalStore(subscribe, getSnapshot) subscribes a component and unsubscribes it when it unmounts |
| Django | Model signals such as post_save | post_save.connect(receiver, sender=Order) / disconnect(...); receivers are held by weak reference by default |
| Qt (C++) | Any QObject with signals | QObject::connect(sender, signal, receiver, slot); connections are removed when either object is destroyed |
The pattern is older than most of these APIs. Smalltalk-80's model-view-controller registered views as dependents of their model and told them to update on every change, and that is the example the Gang of Four book uses for Observer. Today the same shape drives MVC and MVVM data binding, spreadsheet cells that recompute when a referenced cell changes, and the notification fan-out in Design a Notification Service (Class Design).
When to use it, and when not to
Reach for Observer when
- Several parts of the system must react to one event, and the list keeps growing
- Who reacts changes at runtime: user settings, plugins, open screens
- The object that does the work should not depend on the reactions
- Reactions belong to different modules or teams
- A UI must stay in sync with a model that changes
Think twice when
- There is one fixed reaction: a direct call is clearer
- The caller needs an answer back (a validation result, a price): that is a request, not a notification
- Steps must happen in a strict order or all-or-nothing (a transaction)
- Notifications would cascade through chains of observers, which is hard to trace
- Reactions must survive crashes or run in another service: use a queue
Observer vs similar patterns
| Pattern | Who knows whom | Who receives a message | Typical setting |
|---|---|---|---|
| Observer | The subject holds direct references to its observers, typed as an interface; observers usually know the subject | Every subscribed observer | In one process, usually synchronous |
| Publish/Subscribe | Nobody knows anybody: publishers and subscribers only know a broker and a topic name | Every subscriber of the topic, possibly later | Across modules or services, usually asynchronous |
| Mediator | Colleagues know only the mediator; the mediator knows all colleagues and holds the coordination logic | Whichever colleagues the mediator decides to call | Many objects with tangled two-way interactions (a dialog's widgets, a chat room) |
| Chain of Responsibility | Each handler knows the next one in the chain | Usually one handler: the first that can deal with it (or each in turn, as in middleware) | Request handling: middleware, approvals, input events bubbling up |
| Event sourcing (see Event-Driven Architecture, CQRS & Event Sourcing) | Writers append events to a log; readers replay or follow it | Any projection or consumer reading the log | Persistence: the event log is the source of truth, not a notification mechanism |
Implementation
The scenario as a complete program: an OrderListener interface, an OrderService subject with subscribe, unsubscribe and notify, three listeners, and push added as one new class. Each version also guards against a listener unsubscribing during notification. In C++ the subject stores std::weak_ptrs: it does not own its listeners, so it must neither keep them alive (a leak) nor call one that was destroyed (a dangling pointer); an expired listener is skipped and pruned.
from typing import Protocol
class OrderListener(Protocol):
def on_order_placed(self, order_id: str) -> None: ...
class OrderService:
def __init__(self) -> None:
self._listeners: list[OrderListener] = []
def subscribe(self, listener: OrderListener) -> None:
self._listeners.append(listener)
def unsubscribe(self, listener: OrderListener) -> None:
if listener in self._listeners:
self._listeners.remove(listener)
def place_order(self, order_id: str) -> None:
# ...save the order, take payment...
for listener in list(self._listeners): # a copy: listeners may unsubscribe meanwhile
listener.on_order_placed(order_id)
class EmailNotifier:
def on_order_placed(self, order_id: str) -> None:
print(f"Email: receipt for order {order_id}")
class SmsNotifier:
def on_order_placed(self, order_id: str) -> None:
print(f"SMS: order {order_id} confirmed")
class AnalyticsTracker:
def __init__(self) -> None:
self.count = 0
def on_order_placed(self, order_id: str) -> None:
self.count += 1
print(f"Analytics: {self.count} order(s) so far")
# The change request: one new class, no existing class edited.
class PushNotifier:
def on_order_placed(self, order_id: str) -> None:
print(f"Push: order {order_id} placed")
if __name__ == "__main__":
orders = OrderService()
email, sms, stats = EmailNotifier(), SmsNotifier(), AnalyticsTracker()
orders.subscribe(email)
orders.subscribe(sms)
orders.subscribe(stats)
orders.place_order("A1") # email, SMS and analytics react
orders.unsubscribe(sms) # the buyer turns off text messages
orders.place_order("A2") # email and analytics only
orders.subscribe(PushNotifier())
orders.place_order("A3") # email, analytics and pushKey takeaways
- Observer lets a subject notify any number of observers through one small interface; the subject keeps a list and loops over it, and never names a concrete observer.
- Who reacts is decided at runtime with
subscribeandunsubscribe. In the visualizer, unsubscribingsmsmeans order A2 reaches onlyemailandstats, with no class edited. - New reactions are new classes. For the "also send a push notification" request: 0 existing classes edited with Observer, versus
OrderServiceedited by 2 lines without it. - Notification is usually synchronous and in subscription order: the subject waits for every observer, and an exception in one can stop the rest unless the subject catches per observer.
- Every subscription must end. The subject's list keeps observers alive, so forgotten subscriptions leak memory and keep firing; return an unsubscribe handle, or use weak references.
- Observer is in-process and the subject knows its observers. Put a broker in between and it becomes publish/subscribe; centralize the interaction logic and it becomes Mediator.
Common pitfalls
- Forgetting to unsubscribe (the lapsed listener): a closed screen or a finished request that stays subscribed is never garbage collected and keeps reacting to events, sometimes against stale state.
- Modifying the observer list while notifying it: a listener that unsubscribes itself inside the loop can make an index-based loop skip the next listener, or throw
ConcurrentModificationExceptionin Java. Iterate over a snapshot or a copy-on-write list. - Letting one observer's exception or slowness break the subject: in a synchronous loop, a throwing analytics listener can abort notifications after the order was already saved. Catch per observer, or deliver asynchronously.
- Notification cascades: an observer that changes the subject (or another subject) triggers more notifications, which are hard to trace and can loop forever. Notify only on real changes, and keep observers from writing back into what they observe.
- Relying on notification order: subscription order is an implementation detail. If one reaction must happen after another, make that an explicit step, not a side effect of who subscribed first.
Interview tips
- In LLD rounds (notification service, stock ticker, auction, library reservations, parking-lot displays) define the listener interface first, show
subscribe/unsubscribe/notifyon the subject, then add a second observer to show nothing else changes. - Volunteer the production concerns before you are asked: unsubscribing and memory leaks, an exception in one observer, slow observers (go async or use a queue), and thread safety of the list (copy-on-write or a lock plus a snapshot).
- Expect "Observer vs pub/sub?" and "Observer vs Mediator?". Answer with who knows whom: Observer's subject holds its observers, pub/sub has a broker in between, and Mediator holds the coordination logic itself.
Real-world applications
- UI events: DOM
addEventListener, Swing and Android listeners, C# events. - Model-view binding: MVC and MVVM views that redraw when their model changes, and state stores (Redux
subscribe, React'suseSyncExternalStore). - Reactive streams: RxJS observables and subjects, Java's
FlowAPI, .NETIObservable<T>. - Domain events inside a service: an order is placed, and email, analytics, loyalty points and inventory react independently.
- Framework hooks: Django signals such as
post_save, Node.jsEventEmitterevents on streams and servers, plugin systems. - Change watchers:
MutationObserverandResizeObserverin browsers, file watchers, spreadsheet cells that recompute when a referenced cell changes.
Test yourself
In the visualizer, the client calls orders.unsubscribe(sms) and then places order A2. What happens?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.