RxJS - Do I need to unsubscribe

爷,独闯天下 提交于 2019-12-12 20:22:58

问题


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"?


回答1:


Yes. You need to call unsubscribe on the returned subscription.

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.

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.

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.

The only situations in which observables will release resources without an unsubscribe call are when observables complete or error.



来源:https://stackoverflow.com/questions/44536497/rxjs-do-i-need-to-unsubscribe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!