Entwickler transparente Retrospektive
Dennis, Kiya | 10.7.2023

Angular's Convenient Way to End Subscriptions with "takeUntilDestroyed"

Web > Angular's Convenient Way to End Subscriptions with "takeUntilDestroyed"

One important aspect of working with observables in Angular is properly ending subscriptions to avoid memory leaks. Historically, developers have used "takeUntil" in combination with a Subject to end subscriptions. However, there is a new and more convenient method in Angular that eliminates the need for Subjects and manually triggering the onDestroy lifecycle hook. This method is called "takeUntilDestroyed".

"takeUntilDestroyed" is an extension that can be used as an alternative to "takeUntil" and allows for automatically ending subscriptions without using the onDestroy lifecycle hook. This makes implementation easier and ensures that no subscriptions are accidentally left open.

The main advantage of "takeUntilDestroyed" is that it handles the onDestroy lifecycle hook for you. This is particularly helpful in cases where using the onDestroy hook is not possible or practical, such as when using arrow functions or callback functions.

Here is an example of how "takeUntilDestroyed" can be used in an Angular component:

1import { Component, OnInit, OnDestroy, Inject } from '@angular/core';
2import { takeUntilDestroyed } from 'take-until-destroyed';
3import { AuthService } from 'path/to/auth-service';
4import { DestroyRef } from 'path/to/destroy-ref';
7  selector: 'app-example',
8  template: '...',
10export class ExampleComponent implements OnInit, OnDestroy {
11  constructor(
12    private authService: AuthService,
13    @Inject(DestroyRef) private destroyRef: DestroyRef
14  ) {}
16  ngOnInit() {
17    this.authService
18      .login(username)
19      .pipe(takeUntilDestroyed(this.destroyRef))
20      .subscribe({
21        // ... subscription handlers go here
22      });
23  }
25  ngOnDestroy() {
26    // onDestroy no longer needed here
27  }

In this example, the "takeUntilDestroyed" method is used to enable automatic subscription termination. Instead of using the onDestroy lifecycle hook, the "DestroyRef" instance is injected and passed to "takeUntilDestroyed". This ensures that the subscription is automatically terminated when the component is destroyed.

It is important to note that "takeUntilDestroyed" can only be used within a context that supports injection, such as a constructor, a factory function, a field initializer, or a function used with "runInInjectionContext". If the direct injection context is not available, "DestroyRef" can be used to gain the necessary control over destruction.

By using "takeUntilDestroyed", ending subscriptions in Angular becomes even easier and less error-prone. It saves developers time and ensures clean subscription management to avoid memory leaks.

  • Properly ending subscriptions in Angular with "takeUntilDestroyed"
  • How "takeUntilDestroyed" simplifies subscription management
  • Example usage of "takeUntilDestroyed" in an Angular component
Dennis Hundertmark
Dennis (Softwareentwickler)

Als Frontend-Experte und Angular-Enthusiast gestalte ich Webanwendungen, die Technik und Design gekonnt zusammenführen. Meine Stärke liegt in der Entwicklung benutzerzentrierter Lösungen, die sowohl f... mehr anzeigen


... ist unsere engagierte und leidenschaftliche Künstliche Intelligenz und Expertin für Softwareentwicklung. Mit einem unermüdlichen Interesse für technologische Innovationen bringt sie Enthusiasmus u... mehr anzeigen

Standort Hannover

newcubator GmbH
Bödekerstraße 22
30161 Hannover

Standort Dortmund

newcubator GmbH
Westenhellweg 85-89
44137 Dortmund