← Back to Angular, page 2

angular-0028 · Medium mid

How do you prevent memory leaks from subscriptions in Angular, and what are takeUntilDestroyed and DestroyRef?

A subscription to a stream that never completes keeps the callback and the component alive after the component is gone. Prevent it with the async pipe, toSignal, or takeUntilDestroyed(), which completes the stream when the component is destroyed. DestroyRef.onDestroy registers any other cleanup. Outside an injection context pass a DestroyRef explicitly.

Full answer

A memory leak here means a destroyed component cannot be garbage collected because a long-lived source still holds a reference to it through a subscription callback. The callback keeps running too, updating a screen that no longer exists.

Sources that do not complete by themselves: interval, fromEvent, Subjects, valueChanges, router events, and store selectors. HTTP calls complete after one response and are normally safe.

Ways to clean up, from best to worst:

  1. Do not subscribe. Use the async pipe in the template or toSignal(). Both unsubscribe for you.
  2. takeUntilDestroyed() from @angular/core/rxjs-interop. Add it as the last operator before subscribe. Called without arguments it must run in an injection context, such as a constructor or a field initializer.
  3. Outside an injection context (inside ngOnInit or another method), inject DestroyRef as a field and pass it: takeUntilDestroyed(this.destroyRef).
  4. Store the Subscription and call unsubscribe() in ngOnDestroy.
  5. The older pattern is a destroy$ Subject with takeUntil(this.destroy$), which still works and appears in many code bases.

DestroyRef.onDestroy(callback) is the general tool. It runs the callback when the owner (a component, directive, or service) is destroyed. It is useful for event listeners, timers, and third-party objects.

Place takeUntilDestroyed last in the pipe, after operators such as switchMap, so no later operator can start a new inner subscription after the signal fires.

To check for leaks, use the browser's memory profiler or log in a finalize.

typescript
import { Component, DestroyRef, OnInit, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, fromEvent, interval } from 'rxjs';

@Component({
  selector: 'app-live-clock',
  template: `
    <p>Seconds on page: {{ seconds() }}</p>
    <p>Window resized {{ resizes() }} times</p>
  `,
})
export class LiveClockComponent implements OnInit {
  private readonly destroyRef = inject(DestroyRef);

  readonly seconds = signal(0);
  readonly resizes = signal(0);

  constructor() {
    // Injection context: no argument needed.
    interval(1000)
      .pipe(takeUntilDestroyed())
      .subscribe(() => this.seconds.update((s) => s + 1));
  }

  ngOnInit(): void {
    // Not an injection context: pass the DestroyRef explicitly.
    fromEvent(window, 'resize')
      .pipe(debounceTime(200), takeUntilDestroyed(this.destroyRef))
      .subscribe(() => this.resizes.update((r) => r + 1));

    // Any other cleanup can be registered on the same reference.
    this.destroyRef.onDestroy(() => console.log('LiveClockComponent destroyed'));
  }
}

Angular 20.3 and RxJS 7. Resize the window to see the counter change, and navigate away to confirm the callbacks stop.

Key points

  • Long-lived sources need cleanup; HTTP usually does not.
  • Prefer async pipe or `toSignal`. Otherwise use `takeUntilDestroyed()`.
  • Outside an injection context pass `DestroyRef` to `takeUntilDestroyed`.
  • `DestroyRef.onDestroy` cleans up timers, listeners, and other objects.

Common mistakes

  • Calling `takeUntilDestroyed()` without an argument inside `ngOnInit`. It throws because there is no injection context.
  • Putting `takeUntil` before `switchMap`, which can leave the inner stream running.
  • Believing every subscription must be cleaned manually. HTTP and `take(1)` complete by themselves.

Follow-ups

  • Why does the async pipe not leak?
  • How does `takeUntilDestroyed` work inside a service?
  • How would you find a leak in a running app?

Tips

  • Start with "avoid subscribing" and only then list the cleanup tools. It shows good design thinking.
  • Mention `takeUntil(destroy$)` as the older pattern you can still read.
  • Place `takeUntilDestroyed` last in the pipe, and say why.

Evaluation rubric

  • Names which sources leak and which do not.
  • Uses takeUntilDestroyed and DestroyRef correctly.
  • Understands injection context rules.