RxJS refCount

2020-10-14 10:29 更新

使 ConnectableObservable行为像普通的可观察对象,并自动连接它。

refCount<T>(): MonoTypeOperatorFunction<T>

参量

没有参数。

returns

  1. MonoTypeOperatorFunction<T>

描述

在内部,它计算对可观察对象的订阅,如果订阅数大于0,则订阅源(仅一次)。如果订阅数小于1,则取消订阅源。这样,您可以确保发布的 refCount 之前的所有内容仅具有单个订阅,而与目标可观察者的订阅者数量无关。

请注意,使用 share运算符与按顺序使用 publish 运算符(使可观察的热点)和 refCount 运算符完全相同。

refCount大理石图

在下面的示例中,使用 publish 运算符将两个间隔变为可连接的可观察对象。第一个使用 refCount 运算符,第二个不使用它。您会注意到,可连接可观察对象在调用其连接函数之前不会执行任何操作。

  1. import { interval } from 'rxjs';
  2. import { tap, publish, refCount } from 'rxjs/operators';
  3. // Turn the interval observable into a ConnectableObservable (hot)
  4. const refCountInterval = interval(400).pipe(
  5. tap((num) => console.log(`refCount ${num}`)),
  6. publish(),
  7. refCount()
  8. );
  9. const publishedInterval = interval(400).pipe(
  10. tap((num) => console.log(`publish ${num}`)),
  11. publish()
  12. );
  13. refCountInterval.subscribe();
  14. refCountInterval.subscribe();
  15. // 'refCount 0' -----> 'refCount 1' -----> etc
  16. // All subscriptions will receive the same value and the tap (and
  17. // every other operator) before the publish operator will be executed
  18. // only once per event independently of the number of subscriptions.
  19. publishedInterval.subscribe();
  20. // Nothing happens until you call .connect() on the observable.

也可以看看

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号