I have a resource-hungry process and I want to cache the latest result for a certain amount of time.
In following example I have the observable getInterval
. This should be the resource-hungry process. The result of the observable gets shared via getSharedInterval
. This last emission is cached for 5 seconds.
But what I want to achieve, is that the getInterval
observable should complete immediately when the outer observable unscrubscibes, but the latest result should be cached for the next 5 seconds.
Is this possible?
const getInterval = new Observable((source) => {
const interval = setInterval(() => {
source.next('next');
}, 1000);
source.add(() => {
clearInterval(interval);
});
}).pipe(
tap(() => console.log('I am running')),
finalize(() => console.log('completed'))
);
const getSharedInterval = getInterval.pipe(
share({
resetOnRefCountZero: () => timer(5000),
connector: () => new ReplaySubject(1),
resetOnComplete: true,
})
);
getSharedInterval
.pipe(
take(1),
tap(() => console.log('I dont no want anymore'))
)
.subscribe(console.log);