Wanna keep up to date with the latest webdev stuff? Follow me on Twitter
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:
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
- manually unsubscribing
- using the
- using the
asyncpipe which will handle the whole subscription/unsubscription for us (cleanest way)
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 :)