Angular FAQ: Top Questions
49. What is the difference between BehaviorSubject and Subject?
Subject
and BehaviorSubject
are both from RxJS. While Subject
emits to subscribers only after subscription, BehaviorSubject
holds the last emitted value and emits it immediately to new subscribers.
const sub = new Subject();
sub.next(1); // new subscriber won't receive this
const bsub = new BehaviorSubject(0);
bsub.subscribe(x => console.log(x)); // will receive 0 immediately
BehaviorSubject
is ideal for representing current state and broadcasting it.