Unsubscribing stops your app from listening to things it no longer needs. This helps keep your app fast and avoids memory leaks, which slow it down over time.
Unsubscribing and memory leaks in Angular
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-example', template: `<p>Example works!</p>` }) export class ExampleComponent implements OnDestroy { private subscription: Subscription; constructor() { this.subscription = someObservable.subscribe(data => { // handle data }); } ngOnDestroy() { this.subscription.unsubscribe(); } }
Always unsubscribe in the ngOnDestroy lifecycle method to avoid memory leaks.
You can store multiple subscriptions in a Subscription object and unsubscribe all at once.
this.subscription = observable.subscribe(value => { console.log(value); }); ngOnDestroy() { this.subscription.unsubscribe(); }
private subscriptions = new Subscription(); this.subscriptions.add(observable1.subscribe()); this.subscriptions.add(observable2.subscribe()); ngOnDestroy() { this.subscriptions.unsubscribe(); }
takeUntil with a Subject to automatically unsubscribe when the component is destroyed.import { takeUntil } from 'rxjs/operators'; import { Subject } from 'rxjs'; private destroy$ = new Subject<void>(); observable.pipe(takeUntil(this.destroy$)).subscribe(); ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }
This component counts seconds using an Observable timer. It unsubscribes when the component is removed to stop counting and free memory.
import { Component, OnDestroy } from '@angular/core'; import { interval, Subscription } from 'rxjs'; @Component({ selector: 'app-timer', template: `<p>Seconds passed: {{seconds}}</p>` }) export class TimerComponent implements OnDestroy { seconds = 0; private timerSubscription: Subscription; constructor() { const timer$ = interval(1000); // emits every second this.timerSubscription = timer$.subscribe(() => { this.seconds++; }); } ngOnDestroy() { this.timerSubscription.unsubscribe(); } }
Not unsubscribing can cause your app to slow down or crash because it keeps running code you don't need.
Angular's async pipe automatically unsubscribes for you in templates.
Use tools like browser DevTools to check for memory leaks by watching memory usage over time.
Always unsubscribe from Observables to avoid memory leaks.
Use ngOnDestroy to clean up subscriptions when components are removed.
Use helpers like Subscription or takeUntil to manage multiple subscriptions easily.