59. BehaviorSubject and ReplaySubject
These specialized Subjects are essential for state management in services because they allow new subscribers to instantly receive a previous value.
1. BehaviorSubject<T> (Current State)
A BehaviorSubject requires an initial value upon creation. When a new subscriber joins, it immediately receives the last emitted value before receiving any future emissions.
Use Case: Tracking current user status, shopping cart contents, or application configuration (where every subscriber needs to know the current state immediately).
typescript import { BehaviorSubject } from 'rxjs';
const theme$ = new BehaviorSubject
// Subscriber A receives 'light' immediately theme$.subscribe(theme => console.log('A:', theme));
theme$.next('dark'); // All subscribers get 'dark'
// Subscriber B subscribes later theme$.subscribe(theme => console.log('B:', theme)); // B immediately receives 'dark'
theme$.next('system'); /* Output Sequence (after instantiation): A: light, A: dark, B: dark, A: system, B: system */
// We can synchronously read the current value without subscribing console.log(theme$.value); // 'system'
2. ReplaySubject<T> (History)
A ReplaySubject records a specified number of emitted values and replays them to any new subscriber.
Use Case: Error logging (if a user clicks a button, you might want to see the last 5 logs that occurred just before the click).
typescript import { ReplaySubject } from 'rxjs';
// Replay the last 2 values
const notification$ = new ReplaySubject
notification$.next('A'); notification$.next('B'); notification$.next('C'); // 'A' is dropped from history
// New subscriber D joins notification$.subscribe(msg => console.log('D received:', msg)); // Output: D received: B, D received: C