Pub/Sub
Publish/subscribe is messaging through a channel name. Publishers emit on a topic; subscribers listen on that topic. They do not hold references to each other.
Detailed Explanation
Observer usually has a subject object you subscribe to (cart.subscribe). Pub/sub has a broker and string (or symbol) topics: bus.publish("cart.added", item) and bus.subscribe("cart.added", fn). The publisher does not know who is listening. The subscriber does not import the publisher.
The broker is a Map from topic to a Set of handlers. Wildcards (cart.*) are extra. Process-wide brokers (window custom events, a Redux store, a Node EventEmitter used as a singleton) are pub/sub with one implicit bus.
The gain is decoupling across features and teams. The loss is discoverability. A misspelled topic fails silently. There is no type check unless you add one (TypeScript event maps, a const enum of topic names).
Ordering is synchronous unless you queue. publish typically calls handlers now, in subscription order. A handler that publishes again re-enters the bus. Document whether that is allowed.
In the browser, document.dispatchEvent(new CustomEvent("name", { detail })) plus addEventListener is DOM pub/sub. Across tabs, BroadcastChannel is pub/sub. Across machines, you want a real message bus (Redis, NATS); the in-memory pattern does not survive a process restart.
What it costs you: implicit architecture. Everything becomes an event, and request/response ("I need the user now") is forced through awkward reply topics. Use direct function calls for that. Also, a singleton bus in tests leaks subscriptions between cases unless you reset it.
Reach for pub/sub when many publishers and many subscribers share a language of events and should not import each other. Reach for observer when there is a clear owner object. Reach for a queue plus workers when work must survive a crash.
Code Examples
function createBus() {
const topics = new Map();
return {
subscribe(topic, fn) {
const set = topics.get(topic) ?? new Set();
set.add(fn);
topics.set(topic, set);
return () => set.delete(fn);
},
publish(topic, data) {
for (const fn of [...(topics.get(topic) ?? [])]) fn(data);
},
};
}
const bus = createBus();
bus.subscribe("cart.added", (item) => console.log(item.name));
bus.publish("cart.added", { name: "book" }); // => bookBrowser: CustomEvent as a topic
// Browser: CustomEvent as a topic
// document.addEventListener("cart:added", (e) => console.log(e.detail));
// document.dispatchEvent(new CustomEvent("cart:added", { detail: { name: "book" } }));Common Gotchas
Topic strings are a typo-silent API
export constants (`export const CART_ADDED = "cart.added"`) and reuse them.
A process-wide bus retains handlers
reset in tests; unsubscribe in production teardowns.
Pub/sub is not RPC
if the publisher needs a return value, call a function or use a request id plus a reply topic.
Cross-tab `BroadcastChannel` does not fire in the same tab for some uses
know the host's delivery rules.