Lessons40. ReplaySubject: a history of values
Lessons · 40
40. ReplaySubject: a history of values
ReplaySubject — a history buffer
ReplaySubject(bufferSize) stores the last N values. Every new subscriber receives them by "replay" — like a pre-recorded episode.
The three Subject types compared
| Type | What it remembers | Initial needed? |
|---|---|---|
Subject | nothing | no |
BehaviorSubject | the 1 latest | yes |
ReplaySubject(N) | the N latest | no |
Where it's used
- Analytics: a "history of user actions."
- A cache of the latest values that a new subscriber can inspect.
- Handing "already-happened" events to a late subscription.
Your task
- Create
const history$ = new ReplaySubject(2);— a buffer of 2. - Before subscribing, send
1,2,3in turn viahistory$.next(...). - After subscribing, send
4. - Expected output:
--- Subscribe --- → Value: 2 → Value: 3 → Value: 4. The value1dropped out of the buffer (it holds only the last 2).
Solution spoiler · click to reveal
const { ReplaySubject } = Rx;
const history$ = new ReplaySubject(2);
history$.next(1);
history$.next(2);
history$.next(3);
console.log('--- Subscribe ---');
history$.subscribe(value => console.log('Value: ' + value));
history$.next(4); script.ts
CONSOLE · Console output
Hit Run to see the result...