I want my shareReplay() to keep the value of a HttpService call (wsCall()) for a specific period of time. I often see samples like this on the web:
interval(10000).pipe(
startWith(null),
switchMap(_ => wsCall()),
shareReplay()
);
The problem here is, that the webservice is called again every 10 seconds even if the Observable has no subscribers! Thats the internal behavior of shareReplay() – it subscribes and forwards the results.
But how to (easily) achieve what I’m looking for?
>Solution :
Use the underlying share operator instead of shareReplay
interval(10000).pipe(
startWith(null),
switchMap(_ => wsCall()),
share({
connector: () => new ReplaySubject(1),
// this next line causes it to stop the interval if
// no one is subscribed for more than 5 seconds
resetOnRefCountZero: () => timer(5_000),
resetOnError: false,
resetOnComplete: false,
}),
);