I use shareReplay
to call only once (like a cache) a webservice to retrieve some informations :
In my service :
getProfile(): Observable<Customer> {
return this.callWS().pipe(shareReplay(1));
}
In multiple components :
this.myService.getProfile().subscribe(customer => {
console.log('customer informations has been retrieved from WS :', customer);
});
Now I want to add a method to force refresh the informations (bypass shareReplay only once). I tried with storing my observable in a variable, and set it to null before re-initialize it, but it seems to break components subscriptions..
Any help ?
Thanks
I know this thread is old, but I think I know what the other answer meant about prepend a "reset" subject to push new values. Check this example:
private _refreshProfile$ = new BehaviorSubject<void>(undefined);
public profile$: Observable<Customer> = _refreshProfile$
.pipe(
switchMapTo(this.callWS()),
shareReplay(1),
);
public refreshProfile() {
this._refreshProfile$.next();
}
In the above snippet, all profile$
new subscribers will receive the latest emitted value (upon calling callWS()
once). If you wish to "refresh" the Customer being shared, you would call "refreshProfile()". This would emit a new value going through switchMapTo
, reassigning the replay value and also notifying to any profile$
open subscriber.
Have a nice one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With