How to Use takeUntil in RxJS for Angular
Use the
takeUntil operator in RxJS to automatically complete an observable when another observable emits a value. This is commonly used in Angular to stop subscriptions, for example, when a component is destroyed, by passing a notifier observable like a Subject that emits on cleanup.Syntax
The takeUntil operator takes one argument: a notifier observable. It listens to this notifier and completes the source observable as soon as the notifier emits any value.
sourceObservable.pipe(takeUntil(notifierObservable))sourceObservable: The observable you want to listen to.notifierObservable: The observable that triggers completion when it emits.
typescript
import { takeUntil } from 'rxjs/operators'; sourceObservable.pipe( takeUntil(notifierObservable) ).subscribe(value => { // handle emitted values });
Example
This example shows how to use takeUntil in an Angular component to automatically unsubscribe from an interval observable when the component is destroyed.
typescript
import { Component, OnDestroy } from '@angular/core'; import { interval, Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; @Component({ selector: 'app-takeuntil-example', template: `<p>Check the console for output.</p>` }) export class TakeUntilExampleComponent implements OnDestroy { private destroy$ = new Subject<void>(); constructor() { interval(1000).pipe( takeUntil(this.destroy$) ).subscribe(count => { console.log('Count:', count); }); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } }
Output
Count: 0
Count: 1
Count: 2
... (stops when component is destroyed)
Common Pitfalls
Common mistakes when using takeUntil include:
- Not emitting a value on the notifier observable, so the source never completes.
- Not completing the notifier observable, which can cause memory leaks.
- Using
takeUntilwithout a proper notifier, leading to subscriptions that never end.
Always ensure the notifier emits and completes, typically in ngOnDestroy for Angular components.
typescript
/* Wrong way: notifier never emits, so subscription never ends */ const notifier = new Subject(); sourceObservable.pipe( takeUntil(notifier) ).subscribe(); // notifier.next() is never called, so subscription stays active /* Right way: emit and complete notifier on cleanup */ notifier.next(); notifier.complete();
Quick Reference
takeUntil Cheat Sheet:
takeUntil(notifier$): completes source whennotifier$emits- Use a
Subjectas notifier to control completion - Common in Angular to unsubscribe on
ngOnDestroy - Prevents memory leaks by auto-unsubscribing
Key Takeaways
Use takeUntil with a notifier observable to auto-complete subscriptions.
In Angular, use a Subject notifier that emits in ngOnDestroy to clean up.
Always emit and complete the notifier to avoid memory leaks.
takeUntil helps manage observable lifecycles and prevents subscription leaks.