[英]RxJS - Do I need to unsubscribe
If I have something like this: 如果我有这样的事情:
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;
I still need to call subscription.unsubscribe()
before or the GC will take care for this "leak"? 我还是需要先致电
subscription.unsubscribe()
,否则GC会解决此“泄漏”问题?
Yes. 是。 You need to call
unsubscribe
on the returned subscription. 您需要在返回的
unsubscribe
上调用unsubscribe
订阅。
Internally, there is a call to window.setInterval
and its implementation will hold a reference to the observable. 在内部,有一个对
window.setInterval
的调用,其实window.setInterval
保存对可观察对象的引用。 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. 将您的引用设置为
null
对此不会有任何影响,因此将不会收集observable,并且将继续调用传递给subscribe
的函数。
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. 通常,如果您订阅了一个可观察的对象,则该可观察的对象将继续调用传递给
subscribe
的next
函数-除非该可观察的对象完成或出错。
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
. 如果您希望观察者停止调用
next
函数并释放与预订关联的所有资源(包括从next
函数中引用的资源),则必须调用unsubscribe
。
The only situations in which observables will release resources without an unsubscribe
call are when observables complete or error. 可观察对象将在不
unsubscribe
情况下释放资源的唯一情况是,当可观察对象完成或出错时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.