injectDestroy
injectDestroy
is a helper function that returns an observable that emits when the component is destroyed.
It helps us to avoid memory leaks by unsubscribing from Observable
s when the component is destroyed.
Usage
If you are familiar with this pattern:
You can replace it with injectDestroy
and remove the boilerplate code:
As you can see, we don’t need to implement OnDestroy
anymore and we don’t need to manually emit from the Subject
when the component is destroyed.
onDestroy
The value returned by injectDestroy()
also includes onDestroy()
function to register arbitrary destroy logic callbacks.
How it works
The helper functions injects the DestroyRef
class from Angular, and on the onDestroy
lifecycle hook, it emits from the Subject
and completes it.
Difference with takeUntilDestroy
from Angular
Angular provides a takeUntilDestroy
operator that does the same thing. But it requires us to pass the DestroyRef
to the operator when we are not in an injection context.
While injectDestroy
doesn’t require us to pass the DestroyRef
to the operator.
With takeUntilDestroyed
we can also initialize the operator and use it later.
So, it’s up to you to choose which one you prefer to use.