Angular › RxJS & Observables
Why is it important to unsubscribe from an RxJS observable, and what are common ways to do this correctly in Angular?
IntermediateAnswer
Forgetting to unsubscribe from a long lived observable, such as one tied to a manually created subscription, can cause a memory leak, since the subscription and anything it references keeps existing even after the component using it is destroyed. Common solutions include using the async pipe, which unsubscribes automatically, or manually unsubscribing inside the ngOnDestroy lifecycle hook.
private subscription: Subscription;
ngOnInit() {
this.subscription = this.dataService.getData().subscribe((data) => this.data = data);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}Real-world example A live dashboard component correctly stops listening to a continuously updating data stream when the user navigates away, because it unsubscribes inside ngOnDestroy, avoiding a hidden, ongoing subscription that would otherwise keep running forever.