Observer and Publish-Subscribe are two closely related but architecturally distinct patterns. The Observer pattern creates a direct relationship between a subject and its observers — the subject owns the subscriber list and notifies them directly. Publish-Subscribe introduces an event bus intermediary, so publishers and subscribers have no knowledge of each other. Both patterns are illustrated with a real-time stock dashboard example using JavaScript. The post covers where each pattern appears in practice (React state management, browser Observer APIs, micro-frontends, cross-component communication), warns about memory leaks from forgotten unsubscriptions, and provides a decision table to help choose between them.
Table of contents
A Common Frontend ScenarioOption 1: The Observer PatternOption 2: Publish-SubscribeThe Key DifferencePublish-SubscribeWhere You’ll Find the Observer PatternThe relationship is still the same: a single source of state owns its subscribers and informs them whenever its data changes.Where Publish-Subscribe ShinesCross-Component CommunicationA Common Mistake: Forgetting to UnsubscribeChoosing the Right PatternPerformance ConsiderationsFinal Thoughts631 Impressions1 Comment