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 |
Code Examples
typescript
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 immediatelytypescript
// Common Angular pattern: selected ID stream
private readonly selectedId$ = new BehaviorSubject<string | null>(null)
readonly selectedIdChanges$ = this.selectedId$.asObservable()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.