We need to unsubscribe from observables to prevent memory leaks and unnecessary resource consumption. Observables in reactive programming (e.g., in RxJS or Angular) can continue emitting values as long as they are active. If a subscription is not explicitly unsubscribed, it can lead to:
Memory Leaks: The observable retains references to subscribers, preventing garbage collection.
Unwanted Side Effects: The subscription may continue executing logic (e.g., API calls, UI updates) even after the component or service using it is no longer in use.
Performance Issues: Accumulated subscriptions can degrade performance over time.
Example (Angular):
import { Component, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'app-example',
template: `...`,
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
constructor() {
this.subscription = interval(1000).subscribe(value => {
console.log(value);
});
}
ngOnDestroy() {
this.subscription.unsubscribe(); // Unsubscribe to avoid memory leaks
}
}