Reactivity
RxJS: observables, subjects & multicasting
Cold vs hot streams, Subject types, and safe subscription management.
An observable is a lazy, cancellable stream. Cold observables (like HttpClient calls) start fresh per subscriber; hot observables share one execution among subscribers. Converting cold → hot is multicasting, done with shareReplay or a Subject.
Cold observables are Netflix — everyone starts the movie from the beginning; hot observables are live TV — you join whatever is airing now.
Key concepts
1
The Subject family is both observable and observer: Subject has no initial value, BehaviorSubject replays the latest (ideal for state), ReplaySubject replays N, and AsyncSubject emits only the final value.
SubjectBehaviorSubjectReplaySubjectAsyncSubject
2
Subscription management is where leaks hide. Prefer the async pipe; for imperative subscriptions use takeUntilDestroyed() (Angular 16+) so teardown is automatic.
Subscription managementasynctakeUntilDestroyed()
3
Pitfall: calling an HTTP method twice (once to subscribe, once in an async pipe) fires two requests because it is cold — use shareReplay(1). Interview follow-up: "how do you turn a cold HTTP stream into a shared cache?" — shareReplay({ bufferSize: 1, refCount: true }).
Pitfall:Interview follow-up:asyncshareReplay(1)shareReplay({ bufferSize: 1, refCount: true })
typescript
// Shared, cached stream (multicast)
readonly user$ = this.http.get<User>('/api/me').pipe(
shareReplay({ bufferSize: 1, refCount: true })
);
// BehaviorSubject as simple state
private readonly _filter = new BehaviorSubject<string>('');
readonly filter$ = this._filter.asObservable();
setFilter(v: string) { this._filter.next(v); }