Angular, how to unsubscribe from multiple subscriptions?

Royer Adames
2 min readDec 12, 2022

Best practices for unsubscribing include doing so in the ngOnDestroy lifecycle hook and using the takeUntil operator for multiple subscriptions.

To unsubscribe from multiple subscriptions in Angular, you can use the takeUntil operator from the RxJS library. This operator allows you to specify a subject that will be used to unsubscribe from an observable automatically when the subject emits a value.

Here is an example of how you might use the takeUntil operator to unsubscribe from multiple subscriptions in an Angular component:

import { Component, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
//...
})
export class MyComponent implements OnDestroy {
private destroySubject: Subject<void> = new Subject();
ngOnInit() {
// Subscribe to an observable
dataService.getData().pipe(
takeUntil(this.destroySubject)
).subscribe(data => {
// Do something with the data...
});
// Subscribe to another observable
dataService.getMoreData().pipe(
takeUntil(this.destroySubject)
).subscribe(data => {
// Do something with the data...
});
}
ngOnDestroy() {
// Unsubscribe from all observables
this.destroySubject.next();
}
}

In this example, we create a destroySubject that will be used to unsubscribe from all of our observables automatically when the component is destroyed. We then use the takeUntil operator to specify the destroySubject as the "unsubscribe" subject for each of our observables.

When the ngOnDestroy lifecycle hook is called, we call the next() method on the destroySubject to emit a value, which will automatically unsubscribe from all of our observables. This allows us to clean up all of our subscriptions in a single, centralized location without having to unsubscribe from each observable individually manually.

Overall, the takeUntil operator is a useful tool for managing multiple subscriptions in Angular and can help make it easier to clean up and unsubscribe from observables when they are no longer needed.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Royer Adames
Royer Adames

No responses yet

Write a response