Do we need to unsubscribe HTTP client in Angular?

Luka Onikadze
2 min readMay 3, 2020
Photo by Devin Avery on Unsplash

As hand washing and social distancing is the major tool for elimination Corona Virus leak, as unsubscribing is the essential tool for avoiding memory leaks when we use Observables. It’s the must thing to do, otherwise, we have unused object references inside our application. But if we use the HTTP client, there is no need to call unsubscribe. Why’s that?

The answer lives inside, how actually Angular creates this observable. If we dig inside Angular source, there is a class called XHRConnection, which is responsible for creating an AJAX request, transform it to Observable and return the response back. Here’s how it’s creation process looks like (don’t read it whole, just take a glance)

The most important piece of code for us is this

So whenever response comes from AJAX request, It will call the next method that’s how we are getting a response back inside our subscribe function. After our function execution will be finished, there is no use for Angular to keep this observable alive, so it calls the complete() method, which unsubscribes, all the subscription by itself, so you don’t need to call unsubscribe anymore.

The same case goes for Subject, BehaviourSubject, and EventEmitter. They all have complete() method, so if you call that method, even if you had 100 subscriptions, they will all unsubscribed automatically.