I want to build a function that caches the last emitted value of a stream and reexecutes the creation of the stream when an trigger event is fired.
function cache<T>(
source$: () => Observable<T>,
trigger$: Observable<unknown>
): Observable<T> {
return trigger$.pipe(startWith(source$), switchMap(source$), shareReplay(1));
}
this works already pretty well the only problem is when i use it like this
trigger$ = interval(1_000).pipe(
takeUntil(this.destroy$.asObservable())
);
cached$ = cache(
() => of(Math.round(Math.random() * 1_000)),
this.trigger$
);
and trigger the destroy event and subscribe afterwards than i get the last value instead that the interval starts anew. If I use share() instead of shareReplay() than it works as i want, only that I don't get a stored value immediately on subscription. So why does shareReplay() behave this way, is it because of the refCount, and how can I make it work like I want to?
Here is an example https://stackblitz.com/edit/angular-ivy-ny39z3?file=src%2Fapp%2Fapp.component.ts. Just start a few streams that stop and than start new streams without reloading I think than it is clear what my problem is . Thanks for your time and help.