← Back to Angular, page 6

angular-0113 · Easy fresher

Which observables do you need to unsubscribe from in Angular, and which clean themselves up?

Observables that complete, such as HttpClient calls, clean up by themselves. Streams that never complete, such as interval, Subjects, form valueChanges, store selections and DOM events, keep running until you unsubscribe. Use the async pipe, toSignal or takeUntilDestroyed so cleanup is automatic.

Full answer

A subscription keeps the callback and everything it references alive. If the source never ends and you never unsubscribe, the component stays in memory after it is destroyed, and the callback keeps running. This is a memory leak.

Clean by themselves (they complete or error):

  • HttpClient requests: one value then complete.
  • of, from([...]), timer(1000) (a single timer), take(n) and first() streams.
  • ActivatedRoute params: Angular destroys them with the route component, so unsubscribing is optional, but harmless.

Need cleanup (they can emit forever):

  • interval, timer(0, 1000).
  • Subjects and BehaviorSubjects from services that live longer than the component.
  • form.valueChanges and statusChanges when the form lives longer than the view.
  • fromEvent(window, 'resize') and other global events.
  • Store or WebSocket streams.
  • router.events (long-lived).

Ways to clean up:

  1. async pipe: subscribes and unsubscribes with the view.
  2. toSignal(obs$): unsubscribes when the injection context is destroyed.
  3. takeUntilDestroyed() (from @angular/core/rxjs-interop) as the last operator of a pipe. Inside the constructor it needs no argument. Outside, pass a DestroyRef.
  4. Subscription fields with unsubscribe() in ngOnDestroy (old style).
  5. take(1) or first() when only one value is needed.

Do not rely on remembering: choose a default (async, toSignal or takeUntilDestroyed) so the safe pattern is also the easy one.

Place takeUntilDestroyed last, so operators after it do not keep the stream alive.

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

@Component({
  selector: 'app-clock',
  template: `Ticks: {{ ticks() }}`,
})
export class ClockComponent {
  readonly ticks = signal(0);
  private readonly destroyRef = inject(DestroyRef);

  constructor() {
    // In a constructor, takeUntilDestroyed() needs no argument.
    interval(1000)
      .pipe(takeUntilDestroyed())
      .subscribe((n) => this.ticks.set(n + 1));
  }

  startLater(): void {
    // Outside an injection context, pass the DestroyRef.
    interval(500)
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe();
  }
}

RxJS 7.8 and Angular 20.3, type-checked. A Karma test checks that the interval stops ticking after the component is destroyed.

Key points

  • Completing sources (HTTP, `of`, single `timer`) clean up on their own.
  • Infinite sources (`interval`, Subjects, events, `valueChanges`) need cleanup.
  • Prefer `async` pipe, `toSignal` and `takeUntilDestroyed`.
  • Put `takeUntilDestroyed` last in the pipe.

Common mistakes

  • Subscribing to a service Subject in `ngOnInit` and never unsubscribing.
  • Calling `takeUntilDestroyed()` without a `DestroyRef` outside an injection context.
  • Putting `takeUntilDestroyed` before other operators.

Follow-ups

  • Why does an HTTP observable not leak?
  • How does `takeUntilDestroyed` know when to complete?
  • How do you find leaks with the browser memory profiler?

Tips

  • Give the two lists clearly: completes and does not complete.
  • Name the three modern defaults.
  • Show you know the operator position rule.

Evaluation rubric

  • Separates self-completing and infinite sources.
  • Names modern cleanup tools.
  • Avoids common mistakes.