0

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?

John
  • 411
  • 2
  • 8
  • 22
  • Have you read that article carefully? It is stated that _There’s a lot of code out there that unfortunately looks like this:_, and your code looks exactly like the one in the article. If the code exists, it doesn't mean that it is good. The solution is provided in the next paragraph of the article. This question already has an answer and should be closed. – Mladen Feb 19 '20 at 13:01
  • I think the linked question here https://stackoverflow.com/questions/38008334/angular-rxjs-when-should-i-unsubscribe-from-subscription already answers your question very well. If you think it doesn't then feel free to comment here and I'll reopen it. – martin Feb 19 '20 at 13:07

1 Answers1

0

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

AliF50
  • 16,947
  • 1
  • 21
  • 37