typescript - RxjS shareReplay : how to reset its value?

标签 typescript asynchronous caching rxjs reactive-programming

我使用 shareReplay 只调用一次(像缓存一样)网络服务来检索一些信息:

在我的服务中:

getProfile(): Observable<Customer> {
    return this.callWS().pipe(shareReplay(1));
}

在多个组件中:

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

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

有什么帮助吗?

谢谢

最佳答案

我知道这个线程是旧的,但我想我知道另一个答案是什么意思,即在前面加上一个“重置”主题以推送新值。检查这个例子:

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

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

public refreshProfile() {
  this._refreshProfile$.next();
}

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

祝你好运

关于typescript - RxjS shareReplay : how to reset its value?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54348406/

相关文章:

angular - NGRX 选择器投影仪功能在 Jasmine 单元测试中返回未定义, Angular 10

javascript - Props 是 React with Typescript 中已弃用的符号

node.js - 如何在 meteor 中使用 mongo 模式验证和 typescript ?

java - HIbernate 实体管理器 : How to cache queries?

caching - 何时使用 Azure 缓存本地缓存

javascript - 将变量清除为 this.x = x 时,Typescript 会抛出错误

在不 sleep 的情况下在 Golang 中测试 Elasticsearch

python - 如何在python中一个接一个地运行两个进程

javascript - 如何延迟或异步加载此 WordPress javascript 代码段以最后加载以加快页面加载时间?

java - 缓存整个表