Tutorial hero
Lesson icon

takeUntilDestroyed

Originally published June 29, 2023 Time 1 mins

Angular has seen a bunch of quality of life improvements added recently, and one such improvement that has landed inside of their rxjs-interop package is the takeUntilDestroyed operator.

I skipped over this one initially, mostly because a lot of the time I avoid subscribing anyway so I wasn’t overly excited. But I used it for the first time this week and it’s pretty great.

If we manually create observable subscriptions, then we should also make sure to unsubscribe from them. The takeUntil pipe with a destroy notifier has been a favourite of Angular developers for a long time.

Angular’s new takeUntilDestroyed pipe does basically this same thing, except it makes it a lot easier - you just pipe takeUntilDestroyed and that’s (usually) it:

takeUntilDestroyed pipe

This will only work if you are using it within an injection context (e.g. a field initialiser or within the constructor).

If you want to use it in other situations, then you would have to manually inject DestroyRef and pass it to the takeUntilDestroyed operator.

Learn to build modern Angular apps with my course