Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RxJs: shareReplay() with cache invalidation after time

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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,
   }),
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading