Wanna keep up to date with the latest webdev stuff? Follow me on Twitter

RxJS is a first class citizen in every Angular application. It's extremely powerful, but there are also some things you should know and be aware of when using it. Memory leaks is one thing that could happen when you subscribe to "long-running" Observables.

There’s already a lot of articles and talks out there about avoiding potential RxJS memory leaks in Angular components. Here are some of my favorite:

RxJS: Avoiding takeUntil Leaks (by Nicholas Jamieson)
Using the takeUntil operator to automatically unsubscribe from an observable is a mechanism that’s explained in Ben Lesh’s Don’t Unsubscribe article. https://blog.angularindepth.com/rxjs-avoiding-takeuntil-leaks-fb5182d047ef
NgTalks: Kwinten Pisman - Keep your memor(ies|y) safe!
Using the takeUntil operator to automatically unsubscribe from an observable is a mechanism that’s explained in Ben Lesh’s Don’t Unsubscribe article. https://youtu.be/OOF2WIFTMaI

Since I was about to prepare a proper example for an Angular workshop, I thought this could be useful for a lot of people out there and registered an Egghead lesson (which I made available for free).
In the lesson I walk through showing you the actual memory leak, and then I walk through fixing the memory leak by

Some key take aways: an observable coming from Angular’s http client doesn’t need to be unsubscribed, as it immediately completes once the HTTP call terminates. Still, often these observables are behind service functions which can easily be refactored into different observables and thus might need to be unsubscribed in the future. So watch out for those scenarios.

Similarly, when using takeUntil, make sure it’s the last operator in the .pipe(..), just as explained by both of the link I referenced above. So here you you go:

Also, here’s a running Stackblitz example.

Like the video?

Consider buying an Egghead subscription! There are tons of interesting videos up there, all around frontend development. Also make sure to check out my videos & courses published there as well and I have some more in the pipe just about to be published :)


If you enjoyed this post you might want to follow me on Twitter for more news around JavaScript and Angular or watch my Egghead.io video lessons. :smiley: