Angular自动取消订阅RxJs

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会自行解决,在完成或者发生错误的时候,rxjs内部会自动取消订阅,所以这两种情况我们是不需要取消订阅的,也就是不需要手动调用unsubscribe()

猜你喜欢

转载自blog.csdn.net/wf19930209/article/details/104939581