Is there a need to explicitly unsubscribe from a service in the component and why? (Angular 7)

Viewed 2629

I recently came across articles explaining observable's and because I am new to Angular I have been trying to find out the best possible way to do everything.

I came across this article: https://blog.angularindepth.com/angular-question-rxjs-subscribe-vs-async-pipe-in-component-templates-c956c8c0c794 which looks at subscribe vs async pipe.

However even after studying this article and one's such as these on whether to subscribe or not I still am finding it hard to get a definite answer.

So I know that your subscription to a service can leak and according to this article if you are going to use subscribe() then you should unsubscribe() during ngOnDestroy().

Otherwise this will happen:

The subscription is never unsubscribed, so if the Observable does not complete on its own, that whole component, and its template and all their associated objects, will live in memory forever.

However I have also seen sometimes people say you do not need to explicitly unsubscribe when calling a service in a component because Angular does it for you? Maybe I am confusing myself but all I want is a definite answer so I know what to implement when using subscribe() so that memory leaks will not be a problem.

So do I need to explicitly unsubscribe() from a service in my component? An explanation would help future people as well if possible. Thank you!

2 Answers

Angular only takes care of unsubscribing from inbuilt observable subscriptions like those returned from the Http service or when using the async pipe but you need to unsubscribe your custom observables explicitly.

You can use async pipe so that your observables unsubscribe event are handled by Angular or there is an alternative way to use takeUntil

Please refer to this article for better explanation of takeUntil - RxJS: Don’t Unsubscribe

Also consider going through this article to avoid takeUntil leaks - RxJS: Avoiding takeUntil Leaks

You have to understand the the observable and observer flow. Maybe the following points will help you:

  • You dont have to unsubscribe if the observer completed: observer.complete() or observer.error() because the error completes the observer too. It means you can write this:

    Observable.create((observer) =>  {
     observer.next(true)
     observer.complete();
    });
    
  • You dont have to unsubscribe from http request. (it is completed too).

  • You have to unsubscribe from router events

  • You have to unsubscribe from (not completed) timing events

Check this article to get more info about this topic: https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3

To check your code you can use the chrome profiling devtools. See the event listeners.

Related