Bird
0
0

What is a recommended way to unsubscribe from an observable in an Angular component to avoid memory leaks?

hard🚀 Application Q9 of 15
Angular - RxJS and Observables Fundamentals
What is a recommended way to unsubscribe from an observable in an Angular component to avoid memory leaks?
ACall <code>subscribe()</code> again to reset the subscription
BStore the subscription and call <code>unsubscribe()</code> in <code>ngOnDestroy()</code>
CUse <code>setTimeout()</code> to delay unsubscription
DNo need to unsubscribe if observable emits only once
Step-by-Step Solution
Solution:
  1. Step 1: Understand subscription lifecycle

    Subscriptions remain active until unsubscribed, potentially causing memory leaks.
  2. Step 2: Proper unsubscription

    Store the subscription object returned by subscribe() and call unsubscribe() in the component's ngOnDestroy() lifecycle hook.
  3. Step 3: Analyze options

    Store the subscription and call unsubscribe() in ngOnDestroy() correctly describes this approach. Call subscribe() again to reset the subscription is incorrect; calling subscribe again creates a new subscription. Use setTimeout() to delay unsubscription is unrelated and ineffective. No need to unsubscribe if observable emits only once is risky; even single emissions can cause leaks if not handled properly.
  4. Final Answer:

    Store the subscription and call unsubscribe() in ngOnDestroy() -> Option B
  5. Quick Check:

    Unsubscribe in ngOnDestroy to prevent leaks [OK]
Quick Trick: Unsubscribe in ngOnDestroy lifecycle hook [OK]
Common Mistakes:
MISTAKES
  • Ignoring unsubscription for multi-emission observables
  • Calling subscribe multiple times instead of unsubscribe
  • Using unrelated timing functions for unsubscription

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes