发布于 1年前

RxJs——Subscription理解

我們前段時間學習了Observable相關的知識,今天我們學習另一個重要的概念:Subscription。

首先,我們看看Subscription官方文檔的介紹如下:

What is a Subscription? A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method,unsubscribe, that takes no argument and just disposes the resource held by the subscription

一般來說,只要訂閱了Observable,都要取消訂閱,對於一個完成的Observable,取消訂閱有三種方式:

第一种,Observable 完成值的发送,执行 Observable.onComplete()

第二種,Observable 發生错误的时候,执行Observable.onError()

第三种,订阅者主动取消订阅,执行subscription.unsubscribe()

在angular项目中,常用到的订阅以及是否需要调用 unsubscribe() 取消订阅,有以下几种:

  1. Angular 中通过 HttpClient 执行 Http Request 返回的 Observables,订阅这些 Observables 拿到 API 返回的数据,不需要调用 unsubscribe() 取消订阅。
  2. Angular AsyncPipe,不需要调用 unsubscribe()取消订阅。
  3. 通过 Subject,BehaviorSubject,AsyncSubject,ReplaySubject 在各个 Component 之间通信,需要调用 unsubscribe()取消订阅。
  4. RxJS 自带的一些操作符:take,takeWhile,first 等等,不需要调用 unsubscribe()取消订阅。

这里需要重点记住的是:手动取消订阅一般在第三种情况的时候,至于具体的原理码,感兴趣的话可以留言给我具体分析

相关文章

©2020 edoou.com   京ICP备16001874号-3