Angular › RxJS & Observables

Why is it important to unsubscribe from an RxJS observable, and what are common ways to do this correctly in Angular?

Intermediate

Answer

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.

Common follow-ups: How does the takeUntil operator provide a cleaner way to manage unsubscribing from multiple observables at once?;Does every observable actually need to be manually unsubscribed, or do some complete automatically?