Subjects and multicasting
Subject and BehaviorSubject as both an observable and an observer at once — the building block of a hand-rolled event bus or state service.
Subjects and multicasting
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A plain Observable is unicast by default — each subscriber triggers its own independent execution. A Subject is multicast — every subscriber shares the exact same stream of emissions.
- A Subject is both an Observable and an Observer at once: you can `.subscribe()` to it like any observable, and you can also call `.next()` on it yourself to push a value in, which a plain Observable never lets you do from the outside.
- BehaviorSubject adds one thing a plain Subject lacks — a current value, available immediately to any new subscriber, even one that subscribes after the value was last pushed.
Most observables don’t share their work — a Subject does
The cold-vs-hot distinction from two lessons back matters directly here. A typical observable you create yourself — wrapping an HTTP call, say — is cold: each subscriber independently re-triggers the underlying work. That’s correct for “fetch this resource,” but it’s the wrong behavior for “notify everyone currently listening about one shared event” — if three components all need to react to the same click, you don’t want three separate click streams, you want one stream, shared.
A Subject is built for exactly that: it’s multicast by default. Every subscriber receives the exact same sequence of emissions from one shared source, rather than each triggering an independent execution of its own.
A Subject is both an Observable and an Observer
const clicks$ = new Subject<void>();
clicks$.subscribe(() => console.log('subscriber A saw a click'));
clicks$.subscribe(() => console.log('subscriber B saw a click'));
clicks$.next(); // both subscribers log, from the same single call
This is the structural thing that makes a Subject different from a plain
Observable: you can .subscribe() to it, the same as any observable, and
you can call .next() on it yourself from the outside to push a new value in.
A plain Observable’s emissions only come from the function you passed to its
constructor — there’s no external .next() to call. A Subject hands you both
halves of the relationship at once, which is exactly what makes it the natural
building block for a hand-rolled event bus: call .next() wherever the event
happens, subscribe wherever you need to react to it.
BehaviorSubject: the one with a memory
A plain Subject has no memory of past emissions — subscribe after a .next()
call already happened, and you’ve simply missed it, with nothing to catch you
up. For state (as opposed to one-off events), that’s usually wrong: a component
that mounts after the current user was already set still needs to know who the
current user is, right now, not only future changes to it.
const currentUser$ = new BehaviorSubject<User | null>(null);
currentUser$.subscribe((user) => console.log('got', user)); // logs `null` immediately
currentUser$.next({ name: 'Ada' }); // logs the new user
BehaviorSubject requires an initial value at construction, and — this is the
whole point of it existing — any new subscriber immediately receives whatever
the current value is, synchronously, the moment it subscribes, not just
future emissions after that point. This is precisely the shape used for the
shared-state service pattern from a few lessons back: a BehaviorSubject
holding the current value, exposed to the rest of the app as a read-only
observable via .asObservable().
This lesson’s video is a real conference talk building exactly this pattern —
an event-bus/state-service built on Subject/BehaviorSubject — from first
principles; it runs longer than this roadmap’s typical pick because the depth is
the point here, not padding. The linked “deeper” video is a tighter, more
concise comparison of all four Subject variants (including ReplaySubject and
AsyncSubject, which this lesson doesn’t cover directly) if you want the full
picture afterward.
Check yourself
Two components both subscribe to the same cold Observable wrapping an HTTP call. How many HTTP requests actually fire? What if they subscribe to a Subject instead, fed by one shared HTTP call?
Two — a cold Observable's subscription independently re-triggers its underlying work, so each subscriber causes its own request. A Subject multicasts: one shared execution feeds its value to every subscriber, so if only one HTTP call feeds the Subject, both components receive the same single response with no duplicate request.
A new component subscribes to a BehaviorSubject that already has a current value, versus subscribing to a plain Subject that already emitted that same value earlier. What does each new subscriber receive immediately?
The BehaviorSubject subscriber receives the current value right away, synchronously, on subscription — that's the whole point of BehaviorSubject existing. The plain Subject subscriber receives nothing until the *next* `.next()` call — a Subject has no memory of past emissions, so subscribing late means missing whatever already happened.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.