How to use takeUntil operator in Angular
Managing observable subscriptions properly is crucial for preventing memory leaks in Angular applications. With over 25 years of experience building enterprise applications and as the creator of CoreUI, I’ve seen countless memory issues from improper subscription handling. The most reliable solution is using the takeUntil operator with a destroy subject that completes when the component is destroyed. This pattern ensures all subscriptions are automatically cleaned up without manual unsubscribe calls.
Use takeUntil operator with a destroy Subject to automatically unsubscribe from observables when component is destroyed.
import { Component, OnDestroy } from '@angular/core'
import { Subject, takeUntil } from 'rxjs'
import { DataService } from './data.service'
@Component({
selector: 'app-user-list',
template: '<div>{{ users.length }} users loaded</div>'
})
export class UserListComponent implements OnDestroy {
users: any[] = []
private destroy$ = new Subject<void>()
constructor(private dataService: DataService) {
this.dataService.getUsers()
.pipe(takeUntil(this.destroy$))
.subscribe(users => this.users = users)
}
ngOnDestroy() {
this.destroy$.next()
this.destroy$.complete()
}
}
This implementation creates a private destroy$ Subject that acts as a notification stream for component destruction. The takeUntil(this.destroy$) operator tells the observable to complete when the destroy Subject emits a value. In ngOnDestroy, we emit a value and complete the destroy Subject, which automatically unsubscribes all observables using takeUntil.
Best Practice Note:
This is the standard pattern we use throughout CoreUI Angular components to ensure proper cleanup and prevent memory leaks in production applications. Always place takeUntil as the last operator in your pipe for optimal performance.



