I have a situation with shareReplay(1)
. Note that "recalculating" result$
is expensive so I don't want to do it unless required hence I'm using shareReplay(1)
in the first place.
refreshSubject = new BehaviorSubject<void>(undefined);
// Assume this has many subscriptions.
obs$ = refreshSubject.pipe(
switchMap(() => timer(1000)), // My actual logic here is more complicated but the important part is that there's some time delay before result$ emits)
switchMap(() => result$),
shareReplay(1),
);
Now if I call refreshSubject.next()
(to "reset" the value of obs$
after some logic that would change the value of result$
) and want to immediately use a new/"up to date" value of obs$
like so
refreshSubject.next();
obs$.pipe(take(1)).subscribe(value => {
...
});
The subscription seems to receive the old value, presumably because result$
hasn't emitted yet (due to the time delay) so shareReplay(1)
hasn't yet "realised" that its value is "stale".
Is there an elegant way to "tell" the shareReplay
Observable that its stored value is no longer relevant (so any subscriptions after the refresh will use the next emitted value whether it occurs before/after they subscribe)?
I have a situation with shareReplay(1)
. Note that "recalculating" result$
is expensive so I don't want to do it unless required hence I'm using shareReplay(1)
in the first place.
refreshSubject = new BehaviorSubject<void>(undefined);
// Assume this has many subscriptions.
obs$ = refreshSubject.pipe(
switchMap(() => timer(1000)), // My actual logic here is more complicated but the important part is that there's some time delay before result$ emits)
switchMap(() => result$),
shareReplay(1),
);
Now if I call refreshSubject.next()
(to "reset" the value of obs$
after some logic that would change the value of result$
) and want to immediately use a new/"up to date" value of obs$
like so
refreshSubject.next();
obs$.pipe(take(1)).subscribe(value => {
...
});
The subscription seems to receive the old value, presumably because result$
hasn't emitted yet (due to the time delay) so shareReplay(1)
hasn't yet "realised" that its value is "stale".
Is there an elegant way to "tell" the shareReplay
Observable that its stored value is no longer relevant (so any subscriptions after the refresh will use the next emitted value whether it occurs before/after they subscribe)?
1 Answer
Reset to default 1just change shareReplay
to share
, it fits exactly what u need.
https://rxjs.dev/api/operators/share
share
is similar to shareReplay
that it multicast an obs to multiple subscriber, but share
does not store or replay previous emit.
Edit: The comment reminded me, I fot to mention.
After changing it to share
, need to swap the position of subscribe
and next
. like:
obs$.pipe(take(1)).subscribe(value => {
...
});
refreshSubject.next();