Bird
Raised Fist0
Angularframework~20 mins

Observable in component lifecycle in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Observable Lifecycle Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an Observable is subscribed in ngOnInit but not unsubscribed?

Consider an Angular component that subscribes to an Observable inside ngOnInit but does not unsubscribe in ngOnDestroy. What is the 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 throws an error when the component is destroyed.
BThe Observable automatically stops emitting when the component is destroyed.
CThe Observable will keep emitting even after the component is destroyed, causing a memory leak.
DThe Observable completes immediately after the component is initialized.
Attempts:
2 left
💡 Hint

Think about what happens to subscriptions if you don't clean them up.

❓ state_output
intermediate
2:00remaining
What is the console output when using takeUntil in ngOnDestroy?

Given the following Angular component code, what will be printed to the console when the component is destroyed after 3 seconds?

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

@Component({
  selector: 'app-example',
  template: `<p>Example</p>`
})
export class ExampleComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit() {
    interval(1000)
      .pipe(takeUntil(this.destroy$))
      .subscribe(val => console.log(val));

    setTimeout(() => this.ngOnDestroy(), 3000);
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
    console.log('Destroyed');
  }
}
A
Destroyed
0
1
2
B
0
1
2
Destroyed
C
0
1
2
3
Destroyed
D
0
1
Destroyed
Attempts:
2 left
💡 Hint

Consider how takeUntil stops the subscription when destroy$ emits.

🔧 Debug
advanced
2:00remaining
Why does this Angular component fail to unsubscribe properly?

Examine the following Angular component code. Why does the subscription not stop when the component is destroyed?

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

@Component({
  selector: 'app-buggy',
  template: `<p>Buggy</p>`
})
export class BuggyComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit() {
    interval(1000)
      .pipe(takeUntil(this.destroy$))
      .subscribe(val => console.log(val));
  }

  ngOnDestroy() {
    this.destroy$ = new Subject<void>();
    this.destroy$.next();
    this.destroy$.complete();
  }
}
AThe destroy$ Subject is reassigned in ngOnDestroy, so the original subscription never receives the next notification.
BThe subscription is missing the unsubscribe call, so it never stops.
CThe interval Observable does not emit any values, so the subscription never starts.
DThe component is missing the OnDestroy interface implementation.
Attempts:
2 left
💡 Hint

Look carefully at how destroy$ is used in ngOnDestroy.

🧠 Conceptual
advanced
2:00remaining
Which RxJS operator is best to automatically unsubscribe on component destroy?

In Angular, to avoid manual unsubscription, which RxJS operator is designed to complete an Observable when a notifier emits, commonly used with a Subject triggered in ngOnDestroy?

AtakeUntil
BswitchMap
CmergeMap
Dfilter
Attempts:
2 left
💡 Hint

This operator listens to a notifier Observable and completes the source Observable when the notifier emits.

📝 Syntax
expert
2:00remaining
Identify the syntax error preventing proper Observable unsubscription

Which option contains a syntax error that will prevent the Angular component from compiling and unsubscribing correctly?

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

@Component({
  selector: 'app-syntax',
  template: `<p>Syntax Test</p>`
})
export class SyntaxComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject<void>();

  ngOnInit() {
    interval(1000)
      .pipe(takeUntil(this.destroy$))
      .subscribe(val => console.log(val));
  }

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
A
ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
  return;
}
B
ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}
C
ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete()
}
D
ngOnDestroy() {
  this.destroy$.next()
  this.destroy$.complete()
}
Attempts:
2 left
💡 Hint

Check for missing semicolons that cause syntax errors in TypeScript.

Practice

(1/5)
1. What is the main reason to subscribe to an Observable inside the ngOnInit lifecycle hook in an Angular component?
easy
A. To start listening to data streams when the component is initialized
B. To stop listening to data streams when the component is destroyed
C. To create a new Observable instance
D. To update the component's template directly

Solution

  1. Step 1: Understand ngOnInit role

    ngOnInit runs once when the component is created, ideal to start tasks like subscribing to Observables.
  2. Step 2: Purpose of subscribing in ngOnInit

    Subscribing here means the component begins listening to data streams as soon as it is ready.
  3. Final Answer:

    To start listening to data streams when the component is initialized -> Option A
  4. Quick Check:

    Subscribe in ngOnInit = start listening [OK]
Hint: Subscribe in ngOnInit to start data listening early [OK]
Common Mistakes:
  • Subscribing in ngOnDestroy instead of ngOnInit
  • Expecting subscription to stop automatically
  • Confusing subscription with Observable creation
2. Which of the following is the correct way to unsubscribe from an Observable in the ngOnDestroy lifecycle hook?
easy
A. this.subscription.unsubscribe();
B. this.subscription.subscribe();
C. this.subscription.complete();
D. this.subscription.destroy();

Solution

  1. Step 1: Identify the unsubscribe method

    Angular subscriptions have an unsubscribe() method to stop listening to Observables.
  2. Step 2: Match method to lifecycle hook

    In ngOnDestroy, calling unsubscribe() properly cleans up the subscription.
  3. Final Answer:

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

    Unsubscribe method = unsubscribe() [OK]
Hint: Use unsubscribe() to stop Observable listening [OK]
Common Mistakes:
  • Using subscribe() instead of unsubscribe() to stop
  • Calling complete() which does not unsubscribe
  • Using a non-existent destroy() method
3. Consider this Angular component code snippet:
export class TimerComponent implements OnInit, OnDestroy {
  time = 0;
  private subscription!: Subscription;

  ngOnInit() {
    this.subscription = interval(1000).subscribe(() => {
      this.time++;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

What will be the value of time after 3 seconds if the component is displayed and then removed?
medium
A. undefined
B. 3
C. 0
D. Subscription error

Solution

  1. Step 1: Understand the interval Observable

    The interval(1000) emits a value every 1000 milliseconds (1 second), triggering the subscription callback.
  2. Step 2: Count increments before unsubscribe

    After 3 seconds, the callback runs 3 times, incrementing time from 0 to 3. The unsubscribe in ngOnDestroy stops further increments.
  3. Final Answer:

    3 -> Option B
  4. Quick Check:

    3 seconds = 3 increments [OK]
Hint: Count interval ticks before unsubscribe stops updates [OK]
Common Mistakes:
  • Assuming time stays 0 without increments
  • Expecting error due to missing unsubscribe
  • Confusing unsubscribe timing with immediate stop
4. Identify the error in this Angular component code:
export class DataComponent implements OnInit {
  data$ = this.service.getData();

  ngOnInit() {
    this.data$.subscribe(data => {
      console.log(data);
    });
  }
}

What is the main problem here?
medium
A. Observable should not be assigned to a property
B. Subscription syntax is incorrect
C. Missing unsubscribe in ngOnDestroy causes memory leak
D. ngOnInit should not contain subscriptions

Solution

  1. Step 1: Check subscription management

    The code subscribes to an Observable but never unsubscribes, risking memory leaks.
  2. Step 2: Lifecycle hook missing unsubscribe

    Without ngOnDestroy to unsubscribe, the subscription stays active even after component destruction.
  3. Final Answer:

    Missing unsubscribe in ngOnDestroy causes memory leak -> Option C
  4. Quick Check:

    Always unsubscribe to avoid leaks [OK]
Hint: Always unsubscribe in ngOnDestroy to prevent leaks [OK]
Common Mistakes:
  • Thinking subscription syntax is wrong
  • Believing Observables can't be class properties
  • Assuming ngOnInit forbids subscriptions
5. You want to create an Angular component that listens to a user input Observable and updates a display value. The Observable may emit multiple times quickly. Which approach best manages the subscription lifecycle and avoids memory leaks?
hard
A. Use a global variable to store data and avoid subscribing
B. Subscribe in the constructor and never unsubscribe
C. Subscribe in ngOnInit without unsubscribing, relying on Angular to clean up
D. Subscribe in ngOnInit and unsubscribe in ngOnDestroy using a Subscription object

Solution

  1. Step 1: Proper subscription management

    Subscribing in ngOnInit ensures the component starts listening after creation.
  2. Step 2: Unsubscribe in ngOnDestroy to prevent leaks

    Unsubscribing cleans up resources when the component is removed, avoiding memory leaks.
  3. Final Answer:

    Subscribe in ngOnInit and unsubscribe in ngOnDestroy using a Subscription object -> Option D
  4. Quick Check:

    Subscribe ngOnInit + unsubscribe ngOnDestroy = safe lifecycle [OK]
Hint: Pair subscribe in ngOnInit with unsubscribe in ngOnDestroy [OK]
Common Mistakes:
  • Subscribing in constructor which is too early
  • Not unsubscribing and causing leaks
  • Using global variables instead of Observables
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