🅰️ Angular Intermediate

What is the difference between Subject, BehaviorSubject, ReplaySubject, and AsyncSubject?

Why Interviewers Ask This

Mid-level Angular roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

All four are types of Subject in RxJS — they are both Observable and Observer (can emit values AND be subscribed to). They differ in how they handle late subscribers: Subject: no state — late subscribers don't receive previously emitted values. Only emits to current subscribers. Use for event buses, button clicks, WebSocket messages (no need for historical values). const subject = new Subject<number>(); subject.next(1); subject.subscribe(v => console.log(v)); // won't see 1 subject.next(2); // subscriber sees 2. BehaviorSubject: stores the CURRENT value — new subscribers immediately receive the current value. Requires initial value. Use for state that needs to be available immediately (current user, auth state, theme). const user$ = new BehaviorSubject<User|null>(null); // current state user$.getValue(). ReplaySubject(n): buffers the last N emitted values — new subscribers receive the buffered history. Use for caching/replaying recent values (last N chat messages, recent notifications). const replay = new ReplaySubject<number>(3);. AsyncSubject: emits only the LAST value, and only when the Subject completes. Used rarely — for operations that produce one final result when done (similar to Promise). Choosing: most state management = BehaviorSubject; one-time events = Subject; need last N values = ReplaySubject(N).

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Angular answers easy to follow.