prototype:
import { ReplaySubject } from 'rxjs';
new ReplaySubject([bufferSize], [windowSize], [scheduler])
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);
});
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
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.
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.