The Observer pattern is the foundation of reactive programming — RxJS, React's state management, signal libraries, and Redux all trace back to this pattern. An Observable (subject) maintains a list of Observers (subscribers) and notifies them when its state changes. This article builds it from scratch.
Prerequisites: Patterns #1 — Event Emitter
1. Basic Observable — Subscribe, Unsubscribe, Notify
Loading editor...
2. Observable with State — Basic Store
Loading editor...
3. Computed Values — Derived State
Loading editor...
4. Simple Signal Implementation
Signals are the 2024-era evolution of the observer pattern — fine-grained reactive primitives:
Loading editor...
5. Observer vs Event Emitter vs Pub-Sub
Loading editor...
Observer: Subject maintains a list and calls them. Event Emitter: Listeners register on the emitter object. Pub-Sub: A broker/event bus sits between publishers and subscribers — neither knows about the other.
Key Takeaways
- Observable maintains a list of observers and notifies them when state changes.
- Return an unsubscribe function from
subscribe()— avoids listener leaks. - Computed values auto-recompute when their dependencies change.
- Signals are fine-grained observables — each value tracks its own set of listeners.
- Skip notification if the new value equals the old value to prevent infinite update loops.
Next: Patterns #3 — Singleton, Factory & Constructor — compare object creation patterns and when each fits.
