RxJS 訂閱

2020-09-24 14:34 更新

什么是訂閱?訂閱是代表可拋棄資源的對(duì)象,通常是 Observable 的執(zhí)行。訂閱具有一種重要的方法, unsubscribe它不帶任何參數(shù),而只是處置該訂閱所擁有的資源。在以前的 RxJS 版本中,訂閱稱為“一次性”。

  1. import { interval } from 'rxjs';
  2. const observable = interval(1000);
  3. const subscription = observable.subscribe(x => console.log(x));
  4. // Later:
  5. // This cancels the ongoing Observable execution which
  6. // was started by calling subscribe with an Observer.
  7. subscription.unsubscribe();

訂閱實(shí)際上僅具有 unsubscribe()釋放資源或取消可觀察執(zhí)行的功能。

訂閱也可以放在一起,以便 unsubscribe()對(duì)一個(gè)訂閱中的一個(gè)的調(diào)用可以取消訂閱多個(gè)訂閱。您可以通過(guò)將一個(gè)訂閱“添加”到另一個(gè)訂閱中來(lái)做到這一點(diǎn):

  1. import { interval } from 'rxjs';
  2. const observable1 = interval(400);
  3. const observable2 = interval(300);
  4. const subscription = observable1.subscribe(x => console.log('first: ' + x));
  5. const childSubscription = observable2.subscribe(x => console.log('second: ' + x));
  6. subscription.add(childSubscription);
  7. setTimeout(() => {
  8. // Unsubscribes BOTH subscription and childSubscription
  9. subscription.unsubscribe();
  10. }, 1000);

執(zhí)行后,我們會(huì)在控制臺(tái)中看到:

  1. second: 0
  2. first: 0
  3. second: 1
  4. first: 1
  5. second: 2

訂閱還具有一種 remove(otherSubscription)方法,以便撤消添加子訂閱。

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

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)