Subjects for Multicasting
You'll learn how to use Subjects to broadcast a single stream of values to multiple observers simultaneously.
The Multicasting Problem
Regular Observables are unicast: each subscription creates a separate, independent execution. If you subscribe twice to an HTTP request Observable, you make two HTTP calls. Subjects solve this by acting as both an Observable (observers can subscribe) and an Observer (you can push values into them). They turn unicast streams into multicast ones, where one execution feeds many subscribers.
Subject Types
Subject
A basic Subject has no memory. Observers only receive values emitted after they subscribe. Think of it like a live radio broadcast—tune in late, and you miss what already aired.
import { Subject } from 'rxjs';
const subject = new Subject();
subject.subscribe(val => console.log('Observer A:', val));
subject.next(1); // A: 1
subject.subscribe(val => console.log('Observer B:', val));
subject.next(2); // A: 2, B: 2
BehaviorSubject
A BehaviorSubject remembers the last emitted value. New subscribers immediately receive that cached value. Like a scoreboard showing the current score—anyone looking sees the latest state.
const behavior = new BehaviorSubject(0); // requires initial value
behavior.subscribe(val => console.log('Early:', val)); // Early: 0
behavior.next(10);
behavior.subscribe(val => console.log('Late:', val)); // Late: 10
ReplaySubject
A ReplaySubject records multiple past values (you specify how many) and replays them to new subscribers. Like a DVR that lets you catch up on recent events.
const replay = new ReplaySubject(2); // buffer last 2 values
replay.next(1);
replay.next(2);
replay.next(3);
replay.subscribe(val => console.log('New subscriber:', val));
// New subscriber: 2, New subscriber: 3
Key Takeaway: Use Subject for simple multicasting, BehaviorSubject when subscribers need the current state, and ReplaySubject when they need recent history.