RxjS shareReplay:如何重置其值?

Cét*_*tia 10 caching asynchronous reactive-programming rxjs typescript

过去只shareReplay调用一次(如缓存)一个网络服务来检索一些信息:

在我的服务中:

getProfile(): Observable<Customer> {
    return this.callWS().pipe(shareReplay(1));
}
Run Code Online (Sandbox Code Playgroud)

在多个组件中:

this.myService.getProfile().subscribe(customer => {
    console.log('customer informations has been retrieved from WS :', customer);
});
Run Code Online (Sandbox Code Playgroud)

现在我想添加一个方法来强制刷新信息(只绕过 shareReplay 一次)。我尝试将我的 observable 存储在一个变量中,并在重新初始化之前将其设置为 null,但它似乎破坏了组件订阅..

有什么帮助吗?

谢谢

小智 22

我知道这个线程很旧,但我想我知道另一个答案是什么意思是预先设置一个“重置”主题以推送新值。检查这个例子:

private _refreshProfile$ = new BehaviorSubject<void>(undefined);

public profile$: Observable<Customer> = _refreshProfile$
  .pipe(
    switchMapTo(this.callWS()),
    shareReplay(1),
   );

public refreshProfile() {
  this._refreshProfile$.next();
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,所有profile$新订阅者都将收到最新发出的值(调用callWS()一次)。如果您希望“刷新”正在共享的客户,您可以调用“refreshProfile()”。这将发出一个新值switchMapTo,重新分配重放值并通知任何profile$开放订阅者。

有一个不错的


chr*_*arx 5

其他答案都很好,但不必重置实际的 shareReplayed observable,更简单的方法可能只是缓存结果,如下所示:

protected profile$: Observable<Customer>;

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

  return this.profile$;
}

resetProfile() {
  this.profile$ = null;
}
Run Code Online (Sandbox Code Playgroud)

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