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
asyncpipe. 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 withtakeUntil(this.destroy$), completed inngOnDestroy. The older standard pattern. - A
Subscriptionobject collecting subscriptions with.add()and unsubscribed once inngOnDestroy.
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.





