RxJS-我需要退订吗 [英] RxJS - Do I need to unsubscribe
问题描述
如果我有这样的东西:
class MyComponent {
constructor() {
this.interval = Observbale.interval(1000);
}
}
const c = new MyComponent();
const subscription = c.interval.subscribe(() => { ... })
现在让我们说在某个时候我正在这样做:
Now let's say that at a certain point I'm doing this:
c = null;
我仍然需要先致电subscription.unsubscribe()
,否则GC将解决此泄漏"问题?
I still need to call subscription.unsubscribe()
before or the GC will take care for this "leak"?
推荐答案
是.您需要在返回的订阅上调用unsubscribe
.
Yes. You need to call unsubscribe
on the returned subscription.
在内部,有一个对window.setInterval
的调用,其实现将保留对可观察对象的引用.将您的引用设置为null
不会对此造成影响,因此将不会收集可观察对象,并且将继续调用传递给subscribe
的函数.
Internally, there is a call to window.setInterval
and its implementation will hold a reference to the observable. Setting your reference to null
will have no affect on this, so the observable will not be collected and the function passed to subscribe
will continue to be called.
通常,如果您订阅了一个可观察对象,则该可观察对象将继续调用传递给subscribe
的next
函数-除非该可观察对象完成或出错.
In general, if you subscribe to an observable, that observable will continue to call the next
function that was passed to subscribe
- unless the observable completes or errors.
如果您希望观察者停止调用next
函数并释放与订阅关联的任何资源-包括从next
函数内部引用的资源-您必须调用unsubscribe
If you want the observable to stop calling the next
function and to release any resources associated with the subscription - including resources referenced from within the next
function - you must call unsubscribe
.
只有当可观察对象完成或发生错误时,可观察对象才会释放资源而无需unsubscribe
调用.
The only situations in which observables will release resources without an unsubscribe
call are when observables complete or error.
这篇关于RxJS-我需要退订吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!