Disposing Observables

Learn how to unsubscribe from Observables to release the memory resources held by observable, which are not released by default.

We'll cover the following

In the previous sections, you were able to see how powerful Observables really are. But hang on, there is more.

Contrary to promises, which serve as a one-time shot, Observables run once they are created, and that’s it.

Imagine if we created a promise for an HTTP call that took too long to respond or didn’t respond at all, and we navigated to another page in the meantime. What would happen to the memory in this case? You may think that JavaScript garbage collector will handle it, but for single page applications, that’s not really the case.

Unsubscribe from an Observable

This is where Observables come in handy. With all the perks they offer, they allow you to dispose of them once you are done. This means that Observables allow you to cancel their execution context at any time. So, in the above-mentioned scenario, what would you do with the HTTP request that always completes? Well, you would call the unsubscribe() method to the observable, and all the resources held by that observable would be released.

Get hands-on with 1200+ tech skills courses.