【问题标题】:Call API on interval when subscribed订阅时按间隔调用 API
【发布时间】:2018-03-24 02:27:30
【问题描述】:

所以我想设置一个仅在订阅时才获取数据的流。如果有多个订阅,那么我希望它进行多播以避免过多的 api 调用并缓存最后一个已知的好,以便未来的订阅者无需点击 api 即可获得数据。当有人订阅时,我希望定期刷新数据。

我尝试使用shareReplay(n) 运算符完成所有这些操作。它做了我想做的一切,除了当每个人都取消订阅时它不会取消订阅计时器(refCount === 0)。请参见下面的示例:

const subscription = Rx.Observable.timer(0, 1000)
  .do((x) => { console.log('timer 1', x); })
  .switchMap(() => {
    console.log('call the api');
    return Rx.Observable.of('my api call');
  })
  .shareReplay(1)
  .do((x) => { console.log('timer 2'); })
  .subscribe(
      (x) => { console.log('data', x); }
  );

setTimeout(() => {
    console.log('unsubscribe');
    subscription.unsubscribe();
}, 2500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.7/Rx.min.js"></script>

原因似乎是它额外等待内部 observable 完成:

https://github.com/ReactiveX/rxjs/blob/b25db9f369b07f26cf2fc11714ec1990b78a4536/src/internal/operators/shareReplay.ts#L45

是否有更好的运算符(或运算符序列)来完成此操作?我宁愿避免重新创建 shareReplay 运算符只是为了删除该条件。

【问题讨论】:

  • 看看这个blog.thoughtram.io/angular/2018/03/05/…。我认为它回答了你的观点。
  • @Picci 他们仍在使用shareReplay。您在哪里看到它解决了我的问题?
  • 你是对的。它不会处理您的问题。很抱歉这个错误。

标签: rxjs


【解决方案1】:

在发布此消息后立即发现publishReplay(1).refCount() 符合我的描述。我把这个问题留给遇到这个问题的其他人。

所以publishReplay(1).refCount()shareReplay() 不同。看起来它是从5.4.05.5.0-beta4。显然这是一个错误,这里是相关的公关:https://github.com/ReactiveX/rxjs/pull/2910

而且我不是唯一一个困惑的灵魂: https://github.com/ReactiveX/rxjs/issues/3034

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2011-07-25
    • 2023-04-04
    • 2020-11-27
    • 2021-05-28
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多