RxJS refCount

2020-10-14 10:29 更新

使 ConnectableObservable行為像普通的可觀察對象,并自動連接它。

refCount<T>(): MonoTypeOperatorFunction<T>

參量

沒有參數(shù)。

returns

  1. MonoTypeOperatorFunction<T>

描述

在內(nèi)部,它計算對可觀察對象的訂閱,如果訂閱數(shù)大于0,則訂閱源(僅一次)。如果訂閱數(shù)小于1,則取消訂閱源。這樣,您可以確保發(fā)布的 refCount 之前的所有內(nèi)容僅具有單個訂閱,而與目標可觀察者的訂閱者數(shù)量無關(guān)。

請注意,使用 share運算符與按順序使用 publish 運算符(使可觀察的熱點)和 refCount 運算符完全相同。

refCount大理石圖

在下面的示例中,使用 publish 運算符將兩個間隔變?yōu)榭蛇B接的可觀察對象。第一個使用 refCount 運算符,第二個不使用它。您會注意到,可連接可觀察對象在調(diào)用其連接函數(shù)之前不會執(zhí)行任何操作。

  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.

也可以看看

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號