ReplaySubject

prototype:

import { ReplaySubject } from 'rxjs';

new ReplaySubject([bufferSize], [windowSize], [scheduler])
1
2
3

example:

import { ReplaySubject } from 'rxjs';

let replaySubject = new ReplaySubject( 2 );

replaySubject.next( 0 );
replaySubject.next( 1 );
replaySubject.next( 2 );

// 1, 2
let replaySubscription = replaySubject.subscribe((value) => {
  console.log('replay subscription', value);
});
1
2
3
4
5
6
7
8
9
10
11
12

Wow, what happened here, what happened to the first number?

So a .next() that happens before the subscription is created, is normally lost. But in the case of a ReplaySubject we have a chance to save emitted values in the cache. Upon creation the cache has been decided to save two values.

Let's illustrate how this works:

replaySubject.next( 3 )
let secondSubscriber( (value) => console.log(value) ) // 2,3
1
2

GOTCHA

It matters both when the .next() operation happens, the size of the cache as well as when your subscription is created.

In the example above it was demonstrated how to use the constructor using bufferSize argument in the constructor. However there also exist a windowSize argument where you can specify how long the values should remain in the cache. Set it to null and it remains in the cache indefinite.

Business case

It's quite easy to imagine the business case here. You fetch some data and want the app to remember what was fetched latest, and what you fetched might only be relevant for a certain time and when enough time has passed you clear the cache.