Bird
Raised Fist0
Angularframework~20 mins

Unsubscribing and memory leaks in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Memory Leak Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens if you don't unsubscribe from an Observable in Angular?

Consider an Angular component that subscribes to an Observable but never unsubscribes. What is the most likely outcome?

Angular
import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs';

@Component({
  selector: 'app-timer',
  template: `<p>Timer running</p>`
})
export class TimerComponent implements OnInit {
  ngOnInit() {
    interval(1000).subscribe(val => console.log(val));
  }
}
AThe Observable will keep emitting values even after the component is destroyed, causing a memory leak.
BThe Observable automatically stops emitting when the component is destroyed, so no memory leak occurs.
CAngular automatically unsubscribes from all Observables when the component is destroyed.
DThe Observable will throw an error if not unsubscribed before component destruction.
Attempts:
2 left
💡 Hint

Think about what happens to subscriptions when components are removed from the DOM.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly unsubscribes from an Observable in Angular using ngOnDestroy?

Choose the code that properly unsubscribes from a subscription when the component is destroyed.

Angular
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';

@Component({
  selector: 'app-example',
  template: `<p>Example</p>`
})
export class ExampleComponent implements OnInit, OnDestroy {
  private sub?: Subscription;

  ngOnInit() {
    this.sub = interval(1000).subscribe();
  }

  ngOnDestroy() {
    // Unsubscribe here
  }
}
AngOnDestroy() { this.sub.stop(); }
BngOnDestroy() { this.sub = null; }
CngOnDestroy() { this.sub.unsubscribe(); }
DngOnDestroy() { this.sub.complete(); }
Attempts:
2 left
💡 Hint

Look for the method that stops the subscription safely.

🔧 Debug
advanced
2:00remaining
Why does this Angular component cause a memory leak?

Examine the code below. Why does it cause a memory leak?

Angular
import { Component, OnInit } from '@angular/core';
import { interval } from 'rxjs';

@Component({
  selector: 'app-leaky',
  template: `<p>Leaky Component</p>`
})
export class LeakyComponent implements OnInit {
  ngOnInit() {
    interval(1000).subscribe(val => console.log(val));
  }
}
ABecause the subscription is not stored and cannot be unsubscribed later.
BBecause interval() emits only once and then completes.
CBecause console.log causes the memory leak.
DBecause ngOnInit is not called when the component is created.
Attempts:
2 left
💡 Hint

Think about how to stop an Observable subscription.

🧠 Conceptual
advanced
2:00remaining
What is the best practice to avoid memory leaks with multiple subscriptions in Angular?

You have multiple subscriptions in a component. Which approach best avoids memory leaks?

ACall unsubscribe on each subscription separately in ngOnDestroy without grouping.
BStore all subscriptions in a Subscription object and unsubscribe once in ngOnDestroy.
CRely on Angular to automatically unsubscribe all subscriptions on component destroy.
DUse setTimeout to delay unsubscription until after component destruction.
Attempts:
2 left
💡 Hint

Think about managing multiple subscriptions efficiently.

❓ state_output
expert
3:00remaining
What is the console output after destroying this Angular component?

Consider this Angular component. What will be logged to the console after the component is destroyed?

Angular
import { Component, OnInit, OnDestroy } from '@angular/core';
import { interval, Subscription } from 'rxjs';

@Component({
  selector: 'app-test',
  template: `<p>Test Component</p>`
})
export class TestComponent implements OnInit, OnDestroy {
  private sub: Subscription = new Subscription();

  ngOnInit() {
    const sub1 = interval(500).subscribe(val => console.log('A', val));
    const sub2 = interval(700).subscribe(val => console.log('B', val));
    this.sub.add(sub1);
    this.sub.add(sub2);
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
AOnly 'B' logs stop; 'A' logs continue after destruction.
BLogs 'A' and 'B' continue indefinitely after destruction.
COnly 'A' logs stop; 'B' logs continue after destruction.
DNo logs appear after component destruction; all intervals stop.
Attempts:
2 left
💡 Hint

Consider what happens when you unsubscribe a Subscription that contains multiple subscriptions.

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