Bird
0
0

Which approach best manages the subscription lifecycle and avoids memory leaks?

hard📝 lifecycle Q15 of 15
Angular - RxJS and Observables Fundamentals
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?
AUse a global variable to store data and avoid subscribing
BSubscribe in the constructor and never unsubscribe
CSubscribe in ngOnInit without unsubscribing, relying on Angular to clean up
DSubscribe in ngOnInit and unsubscribe in ngOnDestroy using a Subscription object
Step-by-Step Solution
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]
Quick Trick: Pair subscribe in ngOnInit with unsubscribe in ngOnDestroy [OK]
Common Mistakes:
MISTAKES
  • Subscribing in constructor which is too early
  • Not unsubscribing and causing leaks
  • Using global variables instead of Observables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes