...

/

Classic Pattern for Managing Unsubscriptions

Classic Pattern for Managing Unsubscriptions

Learn about the classic pattern for managing unsubscriptions.

Managing unsubscriptions

There are two commonly used ways to manage unsubscriptions: imperative and declarative patterns. Let’s look at both of these patterns in detail.

Imperative unsubscription management

The imperative unsubscription means manually calling the unsubscribe() method on the subscription object we manage ourselves. The following code snippet illustrates this. We simply store the subscription inside a variable called subscription and unsubscribe from the ngOnDestroy() life cycle hook in the src/app/recipes-list/recipes-list.component.ts file.

Press + to interact
export class RecipesListComponent implements OnInit, OnDestroy {
recipes!: Recipe[];
subscription: Subscription;
constructor(private service: RecipesService) {}
ngOnInit(): void {
this.subscription = this.service.getRecipes().subscribe((result) => {
this.recipes = result;
});
}
ngOnDestroy(): void {
this.subscription.unsubscribe();
}
}

Well, this works fine, but it’s not a recommended pattern. There are better ways of using the power of RxJS.

Declarative unsubscription management

The second way is far more declarative and cleaner; it uses the RxJS takeUntil operator. Before we dive into this pattern, let’s gain an understanding of the role of takeUntil, and there’s no better way to understand it than with a marble diagram.

Press + to interact
The takeUntil marble diagram
The takeUntil marble diagram

The takeUntil() operator takes values from the source observable (the first ...