Search code examples
angularmemory-leaksrxjsrxjs-observables

Does this observable leak memory?


I'm fairly new to observables and according to this article. The examples below leaks memory. However, I saw tonnes of tutorials online showing examples like this.

someObservable.subscribe(data => {
   // do something
});

Does the code above leak memory? Do we always have to unsubscribe? How about http calls too?

this.http.get<Any>('someurl').subscribe(response => {
    // do something
});

What are the general best practices for observables?


Solution

  • HTTP calls and router events are finite, so you don't have to unsubscribe from them.

    Everything else, yes you should unsubscribe from them because they generate memory leaks.

    I like to subscribe and unsubscribe using the async pipe for data I am presenting in the HTML. Using the async pipe, when the component gets destroyed, the observable is automatically unsubscribed. For event subscriptions (actual .subscribe), I like to use the takeUntil operator.

    The following article shows when to unsubscribe but I always unsubscribe when I need to/when component gets destroyed. Better be safe than sorry.

    https://netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3