Suggest an editImprove this articleRefine the answer for “How to avoid memory leaks in subscriptions?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)To avoid **memory leaks in subscriptions**, the main rule is: **unsubscribe in time**. **Key point:** an unmanaged subscription = a hanging stream = a memory leak.Shown above the full answer for quick recall.Answer (EN)ImageTo avoid **memory leaks in subscriptions**, the main rule is: **unsubscribe in time**. Here's how it's done in practice: --- ### 1. **Store the subscription and call** `unsubscribe()` ```ts subscription: Subscription; ngOnInit() { this.subscription = this.myStream$.subscribe(data => ...); } ngOnDestroy() { this.subscription.unsubscribe(); // stream closed } ``` --- ### 2. **Use** `takeUntil()` **with a** `Subject` Good if you have **many subscriptions**: ```ts private destroy$ = new Subject<void>(); ngOnInit() { this.myStream$ .pipe(takeUntil(this.destroy$)) .subscribe(...); } ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); } ``` Everything inside `takeUntil` unsubscribes automatically. --- ### 3. **Use the** `async` **pipe in the template** ```html <div *ngIf="value$ | async as value">{{ value }}</div> ``` Angular itself unsubscribes when the component is destroyed. This is the safest option in a template. --- ### 4. `take(n)` **and** `first()` **- for one-time subscriptions** If you only need **one value** from the stream: ```ts this.data$.pipe(first()).subscribe(...); ``` or ```ts this.data$.pipe(take(1)).subscribe(...); ``` The stream completes on its own, nothing to unsubscribe. --- ### Conclusion: To avoid leaks: - Always unsubscribe in `ngOnDestroy()` - Use `takeUntil()` or `async` - Don't leave infinite `subscribe()` calls without control An unmanaged subscription = a hanging stream = a memory leak.For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.