Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxjS shareReplay : how to reset its value?

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

like image 244
Jscti Avatar asked Jan 24 '19 14:01

Jscti


1 Answers

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

like image 76
Marcelo Peotta Avatar answered Sep 23 '22 01:09

Marcelo Peotta