How do you prevent memory leaks from subscriptions?
Model answer
Prefer the async pipe and toSignal, which clean up themselves. For manual subscriptions, use takeUntilDestroyed() (it works with DestroyRef) or the older takeUntil with a subject triggered in ngOnDestroy. Streams that complete on their own, such as a single HTTP call, do not leak, but long-lived ones (valueChanges, timers, router events, WebSockets) do.
Mention that leaks show up as duplicated calls and rising memory when you navigate back and forth.
Learn this topic
Angular Tutorial: Beginner to Advanced .
Sign in to add your own answer.
More questions
- How do you call an API in Angular?
- What is an Observable, and how is it different from a Promise?
- What is the difference between subscribe and the async pipe?
- What are common RxJS operators you use, and what do they do?
- Explain the difference between switchMap, mergeMap, concatMap and exhaustMap.
- What are HTTP interceptors, and what are they used for?