RxjS shareReplay : how to reset its value?

The other answers are all fine, but rather than having to reset the actual shareReplayed observable, a simpler approach might just be caching the result like so:

protected profile$: Observable<Customer>;

getProfile$(): Observable<Customer> {
  if (!this.profile$) {
    this.profile$ = this.callWS().pipe(shareReplay(1));
  }

  return this.profile$;
}

resetProfile() {
  this.profile$ = null;
}

ref: https://blog.angularindepth.com/fastest-way-to-cache-for-lazy-developers-angular-with-rxjs-444a198ed6a6


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