1

Do we need to cancel our subscriptions to a service when it gets destroyed ?

Based on the destroy event, other components that were listenning to this service can cancel their subscriptions. I just don't see why is it important to do so.

Is this a good practise, or a necessity for a performance purpose ?

Scipion
  • 11,449
  • 19
  • 74
  • 139

1 Answers1

4

Yes you do, because stuff like this can cause memory leaks. It's always a good practice to clean up after yourself to ensure that you don't run into big problems down the road, as I have in the past, especially with Angular 1.

Cleaning up after your subscriptions are fairly straightforward:

import {Subscription} from 'rxjs/Subscription';

In your class:

public configSubscription: Subscription;

Inside constructor or ngOnInit or other appropriate place:

this.configSubscription = this.api.config$.subscribe(
  config => {
    this.config = config;
});

Then clean up with this:

ngOnDestroy() {
  this.configSubscription.unsubscribe();
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • 2
    @Scipion In that case I don't think you need to worry. Once you cast to a promise, the underlying Observable will complete as soon as the promise resolves/rejects. This is because promises by definition only emit a single value, so their resources don't linger as is the case with Observables. PS: Maybe someone else can weigh in here, but there is one edge case: if your Promise takes forever to resolve b/c the source Observable doesn't emit, that resource is still alive. In that case you may need to address it, but I still don't see the danger of memleak unless you keep spanning promises – BeetleJuice Oct 13 '16 at 06:34