0
0
Angularframework~3 mins

Why Unsubscribing and memory leaks in Angular? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app secretly wastes memory and slows down without you knowing?

The Scenario

Imagine you build an Angular app that listens to many data streams, like user clicks or server updates, but you never stop listening even when parts of the app are gone.

The Problem

Without stopping these listeners, your app keeps using memory and CPU for things no longer needed. This slows down the app and can even crash the browser.

The Solution

Unsubscribing from streams when they are no longer needed frees up resources automatically, keeping your app fast and healthy.

Before vs After
Before
this.subscription = observable.subscribe(data => { /* handle data */ }); // never unsubscribed
After
this.subscription = observable.subscribe(data => { /* handle data */ });

ngOnDestroy() {
  this.subscription.unsubscribe();
}
What It Enables

It enables your Angular app to run smoothly without wasting memory or slowing down over time.

Real Life Example

Think of it like turning off the lights when you leave a room; unsubscribing turns off data streams when components are gone.

Key Takeaways

Not unsubscribing causes memory leaks and slow apps.

Unsubscribing cleans up resources automatically.

This keeps Angular apps fast and reliable.