BACK
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

TypeWhat it remembersInitial needed?
Subjectnothingno
BehaviorSubjectthe 1 latestyes
ReplaySubject(N)the N latestno

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

  1. Create const history$ = new ReplaySubject(2); — a buffer of 2.
  2. Before subscribing, send 1, 2, 3 in turn via history$.next(...).
  3. After subscribing, send 4.
  4. Expected output: --- Subscribe --- → Value: 2 → Value: 3 → Value: 4. The value 1 dropped 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 // TypeScript
CONSOLE · Console output
Hit Run to see the result...