In Angular, takeUntil() is an RxJS operator used to automatically complete or unsubscribe from an observable when a notifier observable emits a value. This helps in cleaning up subscriptions and preventing memory leaks.
How it works:
You provide a notifier observable (e.g., a Subject).
When the notifier emits a value (e.g., during component destruction), takeUntil() completes the source observable and unsubscribes.
Example:
import { Component, OnDestroy } from '@angular/core';
import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: `...`
})
export class ExampleComponent implements OnDestroy {
private destroy$ = new Subject<void>();
constructor() {
interval(1000) // Emits every second
.pipe(takeUntil(this.destroy$)) // Completes when destroy$ emits
.subscribe(value => console.log(value));
}
ngOnDestroy() {
this.destroy$.next(); // Emit to complete the observable
this.destroy$.complete(); // Clean up the subject
}
}