Skip to content
mediummid2 min read Updated 2026-10-06T00:00:00.000Z #rxjs #subject #behaviorsubject #angular

Difference between Subject and BehaviorSubject ​

Answer ​

Both Subject and BehaviorSubject are multicast observables you can use as both observer and observable.

SubjectBehaviorSubject
Initial valueNoRequired
Late subscriberMisses prior emissionsGets latest value immediately
Typical useFire-and-forget eventsState 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 immediately
typescript
// Common Angular pattern: selected ID stream
private readonly selectedId$ = new BehaviorSubject<string | null>(null)
readonly selectedIdChanges$ = this.selectedId$.asObservable()

Common Mistakes ​

  • Using Subject for state that new components must hydrate immediately.
  • Exposing the BehaviorSubject publicly instead of asObservable().
  • Forgetting getValue() is imperative—prefer reactive flows in templates with async pipe.

Follow-up Questions ​

  • When would you use ReplaySubject or AsyncSubject?
  • 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.

Built for developers preparing for technical interviews.