Observer
Objects subscribe to a subject and get notified automatically when it changes β the subject never needs to know who's listening.
Intent & Description
π― Intent
Automatically notify any number of interested objects when something changes, without hard-coding who those objects are.
π Context
You’re building a stock ticker, event system, real-time UI updates, or anything where one state change needs to ripple to multiple consumers. Polling is wasteful; direct coupling is brittle.
π‘ Solution
A Subject maintains a list of Observer subscribers. When state changes, it calls notify() on all of them. Observers subscribe and unsubscribe at runtime. The Subject doesn’t know or care which Observers are attached β just that they implement update().
Real-world Use Case
Source
π TL;DR
Subject changes β all subscribers get notified automatically. Fully decoupled. The foundation of every event system and reactive framework. Notification order is undefined β design around that.
Advantages
- Add new subscriber types without touching the subject’s code.
- Subscribe and unsubscribe at runtime β fully dynamic relationships.
Disadvantages
- Notification order is undefined β if subscribers depend on being called in a specific sequence, you’ll have subtle bugs.
class Subject {
constructor() { this.observers = []; }
subscribe(observer) { this.observers.push(observer); }
unsubscribe(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(obs => obs.update(data));
}
}