Getting to Know the takeUntilDestroyed Operator in Angular
Angular v16 introduces a new feature in the @angular/core/rxjs-interop
entry that includes three new operators: fromSignal
, fromObservable
, and takeUntilDestroyed
. These operators are designed to enhance the functionality of RxJS in Angular applications.
The takeUntilDestroyed
operator allows developers to automatically complete an observable when the calling context (which can be a component, directive, service, or a pipe) is destroyed. This helps prevent memory leaks and ensures that resources are released properly.
To use the takeUntilDestroyed
operator, you first need to import it from the @angular/core/rxjs-interop
entry.
Once imported, you can use it by chaining it onto your observable. For example:
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({
...
})
export default class HomeComponent {
constructor() {
interval(1000).pipe(takeUntilDestroyed()).subscribe(console.log);
}
}
In this example, the takeUntilDestroyed
operator is used in the constructor
of the HomeComponent
. This is because the operator is designed to be used inside an injection context. Angular uses the DestroyRef
provider under the hood.
If you want to use the operator in other places, you can pass a DestroyRef
provider explicitly. Here’s an example:
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({
...
})
export default class HomeComponent {
private destroyRef = inject(DestroyRef);
ngOnInit() {
interval(1000).pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe(console.log);
}
}
Follow me on Medium or Twitter to read more about Angular and JS!