takeUntil is an RxJS operator used to automatically unsubscribe from an observable when another observable emits a value. It is commonly used to clean up subscriptions when an Angular component is destroyed, preventing memory leaks.
Example: Unsubscribing on Component Destroy
import { Component, OnDestroy } from '@angular/core';
import { Subject, interval, takeUntil } from 'rxjs';
@Component({
selector: 'app-example',
template: `<p>Check console for values</p>`,
})
export class ExampleComponent implements OnDestroy {
private destroy$ = new Subject<void>();
constructor() {
interval(1000) // Emits every second
.pipe(takeUntil(this.destroy$)) // Stops on destroy$
.subscribe(value => console.log('Value:', value));
}
ngOnDestroy() {
this.destroy$.next(); // Triggers unsubscription
this.destroy$.complete(); // Cleans up the subject
}
}
Key Uses of takeUntil
Prevents memory leaks by automatically unsubscribing.
Used in ngOnDestroy() to clean up subscriptions when a component is destroyed.
Stops ongoing operations when a condition is met (e.g., logout, page navigation).