Angular自動取消訂閱RxJs
在使用 rxjs 時我們經常忘記調用unsubscribe()
而導致內存泄露,很多時候你很難發現它,在RxJs官方有這樣一段話:
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
我們可以看出對于 Subscription 對象我們需要手動調用unsubscribe()
取消訂閱,這樣就不會導致內存泄露。
下面我們講講什么時候該取消訂閱。
Observable的取消訂閱
Observable對象取消訂閱有下面三種方式:
- Observable完成值的發送,執行Observable.onComplete()。
- Observable發生錯誤,執行Observable.OnError()。
- 訂閱者主動取消訂閱,執行subscription.unsubscribe()。
在上面中的Observable.onComplete()
和Observable.OnError()
這兩種情況,Rxjs會自行解決,在完成或者發生錯誤