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



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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.