Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

How do you avoid memory leaks from RxJS subscriptions in Angular?

A subscription that outlives its component keeps the component and everything it references alive. Over a long session with many navigations, that accumulates.

The options, best first:

  • The async pipe. It subscribes and unsubscribes for you, and works with OnPush. If you can bind the observable straight into the template, do that and the problem disappears.
  • takeUntilDestroyed() — since Angular 16, the cleanest programmatic answer:
    this.service.data$
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe(d => this.data = d);
  • A destroy$ subject with takeUntil(this.destroy$), completed in ngOnDestroy. The older standard pattern.
  • A Subscription object collecting subscriptions with .add() and unsubscribed once in ngOnDestroy.

What does not need unsubscribing: observables that complete on their own, such as an HttpClient call, which emits once and completes. It is still safer to apply the same pattern uniformly rather than asking developers to remember which is which.

Note: Long-lived sources are the dangerous ones — router events, a BehaviorSubject in a root service, form valueChanges, and anything from an interval.

All Angular interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as