Unsubscribing and Cleanup
You'll learn why unsubscribing from Observables is essential to prevent memory leaks and how to use the subscription object to clean up properly.
Why Unsubscribing Matters
When you subscribe to an Observable (as you learned in the previous lesson), you create a persistent connection that continues to run until the Observable completes or you explicitly unsubscribe. If you forget to unsubscribe, these active subscriptions pile up like forgotten timers or event listeners—consuming memory and potentially executing code you no longer need.
Think of it like subscribing to a magazine: if you move apartments but never cancel your subscription, magazines keep getting delivered (and billed) to your old address forever.
The Subscription Object
When you call subscribe() on an Observable, it returns a subscription object. This object has an unsubscribe() method that lets you cancel the subscription and trigger any cleanup logic:
const subscription = observable.subscribe(
value => console.log(value)
);
// Later, when you're done:
subscription.unsubscribe();
After calling unsubscribe(), no more values will be emitted to your observer, and any resources held by the Observable (timers, HTTP connections, event listeners) can be released.
Preventing Memory Leaks
Always unsubscribe when:
- A component or module is destroyed
- You no longer need the data stream
- You're replacing one subscription with another
Without unsubscribing, you create memory leaks where old observers continue listening and executing, even though they're no longer relevant to your application state.
Key Takeaway: Always call unsubscribe() on the subscription object returned from subscribe() to prevent memory leaks and clean up resources when you no longer need the Observable stream.