Bird
Raised Fist0
Angularframework~10 mins

Unsubscribing and memory leaks in Angular - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Unsubscribing and memory leaks
Component Initialized
↓
Subscribe to Observable
↓
Component Uses Data
↓
Component Destroyed
↓
Unsubscribe from Observable
↓
Memory Freed
↓
No Memory Leak
↓
Component Destroyed
↓
Subscription Remains Active
↓
Memory Leak Occurs
Shows how subscribing to data streams must be paired with unsubscribing when a component is destroyed to avoid memory leaks.
Execution Sample
Angular
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

@Component({ selector: 'app-demo', template: '' })
export class DemoComponent implements OnDestroy {
  sub: Subscription;
  constructor() {
    this.sub = someObservable.subscribe();
  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
This Angular component subscribes to an observable and unsubscribes when destroyed to prevent memory leaks.
Execution Table
StepActionSubscription StateMemory Status
1Component createdNo subscriptionNo memory used by subscription
2Subscribe to observableSubscription activeMemory allocated for subscription
3Component uses dataSubscription activeMemory in use
4Component destroyedSubscription activeMemory still allocated (potential leak)
5Unsubscribe calledSubscription closedMemory freed
6Component fully cleanedNo subscriptionNo memory leak
💡 Unsubscribe must be called on destroy to free memory and avoid leaks
Variable Tracker
VariableStartAfter Step 2After Step 5Final
subundefinedSubscription object (active)Subscription object (closed)undefined or garbage collected
Key Moments - 3 Insights
Why do we need to unsubscribe in ngOnDestroy?
Because the subscription stays active after the component is destroyed (see step 4 in execution_table), causing memory to stay allocated and leading to leaks.
What happens if we forget to unsubscribe?
The subscription remains active (step 4), so memory is not freed, which can slow down or crash the app over time.
Is unsubscribing necessary for all observables?
Not always. Some observables complete automatically, but for long-lived or infinite streams, unsubscribing is essential to prevent leaks.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the subscription state at step 4?
ASubscription closed
BSubscription active
CNo subscription
DSubscription error
💡 Hint
Check the 'Subscription State' column at step 4 in the execution_table
At which step is memory freed according to the execution_table?
AStep 5
BStep 2
CStep 4
DStep 6
💡 Hint
Look at the 'Memory Status' column to find when memory is freed
If we remove the unsubscribe call, what will happen to the memory status after component destruction?
AMemory freed immediately
BSubscription closes automatically
CMemory remains allocated causing a leak
DComponent will not destroy
💡 Hint
Refer to the exit_note and step 4 in execution_table about missing unsubscribe
Concept Snapshot
Angular components subscribing to observables must unsubscribe in ngOnDestroy.
Failing to unsubscribe keeps subscriptions active.
Active subscriptions hold memory causing leaks.
Unsubscribe frees memory and prevents leaks.
Use Subscription object and call unsubscribe() on destroy.
Full Transcript
In Angular, when a component subscribes to an observable, it creates a subscription that holds resources in memory. If the component is destroyed but the subscription is not unsubscribed, the subscription stays active, causing memory to remain allocated. This leads to memory leaks which can degrade app performance. To prevent this, Angular components implement the ngOnDestroy lifecycle hook where they call unsubscribe() on their subscriptions. This closes the subscription and frees memory. The execution table shows the subscription state and memory status step-by-step, highlighting the importance of unsubscribing. Beginners often confuse when to unsubscribe and why it matters. Remember, unsubscribing is essential for long-lived observables to keep your app healthy and fast.

Practice

(1/5)
1. Why is it important to unsubscribe from Observables in Angular components?
easy
A. To make the component load faster initially.
B. To prevent memory leaks by stopping ongoing subscriptions when the component is destroyed.
C. To increase the number of active subscriptions.
D. To automatically refresh the component view.

Solution

  1. Step 1: Understand Observable subscriptions

    Subscriptions keep listening to data streams, even if the component is gone.
  2. Step 2: Recognize the effect of not unsubscribing

    Not unsubscribing causes memory to be used unnecessarily, leading to leaks.
  3. Final Answer:

    To prevent memory leaks by stopping ongoing subscriptions when the component is destroyed. -> Option B
  4. Quick Check:

    Unsubscribe to avoid memory leaks = B [OK]
Hint: Unsubscribe in ngOnDestroy to avoid leaks [OK]
Common Mistakes:
  • Thinking Angular unsubscribes automatically
  • Believing unsubscribing improves load speed
  • Ignoring memory leaks from active subscriptions
2. Which of the following is the correct way to unsubscribe from a subscription in Angular's ngOnDestroy method?
easy
A. this.subscription.unsubscribe();
B. this.subscription.stop();
C. this.subscription.close();
D. this.subscription.cancel();

Solution

  1. Step 1: Recall Subscription API

    The Subscription object has an unsubscribe() method to stop listening.
  2. Step 2: Identify correct method name

    Only unsubscribe() is valid; others do not exist on Subscription.
  3. Final Answer:

    this.subscription.unsubscribe(); -> Option A
  4. Quick Check:

    Use unsubscribe() to stop subscription = D [OK]
Hint: Use unsubscribe() method to stop subscriptions [OK]
Common Mistakes:
  • Using non-existent methods like stop() or cancel()
  • Forgetting to call unsubscribe() at all
  • Calling unsubscribe() outside ngOnDestroy
3. Consider this Angular component snippet:
export class MyComponent implements OnDestroy {
  private sub = this.service.getData().subscribe(data => console.log(data));

  ngOnDestroy() {
    // missing unsubscribe
  }
}

What will happen if this component is created and destroyed multiple times without adding unsubscribe in ngOnDestroy?
medium
A. Memory usage will increase over time due to active subscriptions not being cleaned up.
B. The component will automatically unsubscribe, so no issues occur.
C. The subscription will throw an error immediately on component destroy.
D. The component will reload data only once and then stop.

Solution

  1. Step 1: Analyze missing unsubscribe

    Without calling unsubscribe, the subscription stays active even after component destruction.
  2. Step 2: Understand consequences

    Repeated creation and destruction cause multiple active subscriptions, increasing memory use.
  3. Final Answer:

    Memory usage will increase over time due to active subscriptions not being cleaned up. -> Option A
  4. Quick Check:

    Missing unsubscribe causes memory leaks = A [OK]
Hint: No unsubscribe means memory leaks grow with component reuse [OK]
Common Mistakes:
  • Assuming Angular auto-unsubscribes
  • Expecting errors on destroy without unsubscribe
  • Thinking subscription stops automatically
4. Identify the problem in this Angular component code related to unsubscribing:
export class DemoComponent implements OnDestroy {
  private subscription: Subscription;

  ngOnInit() {
    this.subscription = this.service.getData().subscribe();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe;
  }
}
medium
A. The subscription is unsubscribed twice.
B. Subscription is declared but never assigned.
C. ngOnDestroy is missing the unsubscribe call.
D. The unsubscribe method is not called; it is referenced without parentheses.

Solution

  1. Step 1: Check unsubscribe usage

    The code uses this.subscription.unsubscribe; without parentheses, so the method is not executed.
  2. Step 2: Understand effect

    Without calling unsubscribe(), the subscription remains active, causing memory leaks.
  3. Final Answer:

    The unsubscribe method is not called; it is referenced without parentheses. -> Option D
  4. Quick Check:

    Call unsubscribe() with () to execute it = A [OK]
Hint: Always call unsubscribe() with parentheses [OK]
Common Mistakes:
  • Forgetting parentheses on unsubscribe
  • Assuming referencing method unsubscribes
  • Not assigning subscription before unsubscribe
5. You have multiple subscriptions in an Angular component. Which is the best way to manage unsubscribing all of them efficiently?
hard
A. Ignore unsubscribing because Angular handles it automatically.
B. Manually call unsubscribe() on each subscription separately in ngOnDestroy.
C. Store all subscriptions in a Subscription object and call unsubscribe() once in ngOnDestroy.
D. Use setTimeout to delay unsubscribing after component destruction.

Solution

  1. Step 1: Understand managing multiple subscriptions

    Using a Subscription object lets you add multiple subscriptions and unsubscribe all at once.
  2. Step 2: Compare with manual unsubscribing

    Manual unsubscribing is error-prone and verbose; Subscription.add() simplifies cleanup.
  3. Final Answer:

    Store all subscriptions in a Subscription object and call unsubscribe() once in ngOnDestroy. -> Option C
  4. Quick Check:

    Use Subscription.add() and one unsubscribe() call = C [OK]
Hint: Use Subscription.add() to group and unsubscribe once [OK]
Common Mistakes:
  • Forgetting to unsubscribe all subscriptions
  • Relying on Angular to auto-unsubscribe
  • Using setTimeout which delays cleanup unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard