Difference between Subject and BehaviorSubject
Answer
Both Subject and BehaviorSubject are multicast observables you can use as both observer and observable.
Subject | BehaviorSubject | |
|---|---|---|
| Initial value | No | Required |
| Late subscriber | Misses prior emissions | Gets latest value immediately |
| Typical use | Fire-and-forget events | State snapshots, selected entity |
Choosing between them
Use a Subject when an emission represents an event that only current subscribers should observe: a refresh command, dismissal notification, or completed action. A component that subscribes later should not pretend that the old event just happened. Use a BehaviorSubject when the stream represents current state and every new subscriber needs an immediate snapshot, such as the selected account, current filter, or authenticated user. Its required initial value forces you to model the state before real data arrives, often with null or a deliberate loading value.
Both types are hot and multicast. Calling next happens independently of whether a particular consumer is ready, and all current subscribers receive the same emission. Neither automatically provides durable persistence, server-state caching, or a complete application store. Keep mutation private in a service and expose only the observable view so components cannot push arbitrary values.
BehaviorSubject#getValue() can be useful at an imperative boundary, but frequent reads are a warning that code is leaving the reactive model. Prefer composing streams with operators and consuming them with Angular's async pipe. For bounded replay of several historical values, use ReplaySubject; for one final value on completion, consider AsyncSubject.
Code Examples
import { Subject, BehaviorSubject } from 'rxjs'
const subject = new Subject<number>()
subject.subscribe(v => console.log('A', v))
subject.next(1)
subject.subscribe(v => console.log('B', v)) // B does not log 1
subject.next(2)
const behavior = new BehaviorSubject(0)
behavior.subscribe(v => console.log('C', v))
behavior.next(1)
behavior.subscribe(v => console.log('D', v)) // D logs 1 immediately// Common Angular pattern: selected ID stream
private readonly selectedId$ = new BehaviorSubject<string | null>(null)
readonly selectedIdChanges$ = this.selectedId$.asObservable()In this example, a child route created after the user selects an item immediately receives the current ID from the BehaviorSubject. Replacing it with a plain Subject would leave the late subscriber empty until the user changed the selection again. Conversely, using a BehaviorSubject for a one-time “toast dismissed” event could incorrectly replay that old event to a newly mounted component.
Common Mistakes
- Using
Subjectfor state that new components must hydrate immediately. - Exposing the
BehaviorSubjectpublicly instead ofasObservable(). - Forgetting
getValue()is imperative—prefer reactive flows in templates with async pipe.
Follow-up Questions
- When would you use
ReplaySubjectorAsyncSubject? - How does this relate to NgRx/component stores?
- Hot vs cold observables—where do subjects fit?
Real Interview Scenarios
You are given a broken dashboard where a child route loads late and never receives the current filter—fixing with BehaviorSubject or shared store state is a classic prompt.
Copyable example
// Difference between Subject and BehaviorSubject
// Subject has no initial value and does not replay to late subscribers; BehaviorSubject requires an initial value and emits the latest value immediately to new subscribers.
readonly results$ = this.query.valueChanges.pipe(debounceTime(250), distinctUntilChanged(), switchMap(query => this.api.search(query)))This Angular snippet uses the APIs and patterns from the RxJS in Angular section rather than a shared fallback component.