All topics
RxJSintermediate

BehaviorSubject and ReplaySubject

Explain how BehaviorSubject and ReplaySubject each solve the 'late subscriber' gap that plain Subjects leave open.

A plain Subject has no memory of past emissions, which is a problem any time a component needs the current value of something immediately upon subscribing, rather than waiting for the next emission that might never come (or might come much later). BehaviorSubject and ReplaySubject both solve this, but in different ways worth distinguishing precisely, since interviewers frequently ask you to pick the right one for a given scenario.

BehaviorSubject is like a digital thermostat display — walk up to it any time and it instantly shows the current temperature, regardless of when it last changed. ReplaySubject is like a DVR that lets a late arrival instantly rewatch the last few minutes of a show they missed, not just freeze on the current frame.

Key Concepts

1
BehaviorSubject<T> requires an initial value at construction time and always holds exactly the most recent value — every new subscriber immediately and synchronously receives that current value the moment they subscribe, even if it was emitted before they subscribed. This maps naturally onto "current state" use cases: a currentUser$, a isLoading$ flag, or any piece of state where there's always a meaningful "current value" that new observers should see immediately. Its .getValue() (or .value) method also lets you synchronously read the current value outside of a subscription entirely, which plain Observables don't support.
BehaviorSubject<T>currentUser$isLoading$.getValue().value
2
ReplaySubject<T>(bufferSize) doesn't require an initial value, but instead replays the last bufferSize emitted values (not just the single most recent one) to every new subscriber upon subscription — useful for something like a chat history or an activity log, where a late subscriber should catch up on several recent events, not just the very latest one.
ReplaySubject<T>(bufferSize)bufferSize
3
A sharp interview answer distinguishes the two along exactly this axis: BehaviorSubject for "there's always a current single value, and it must have an initial value before anyone subscribes," versus ReplaySubject for "a late subscriber needs to catch up on a window of recent history," and notes both are still true multicasting Subjects underneath — they just add memory of differing depth on top of the base Subject behavior.
BehaviorSubjectReplaySubject