Angular · Middle · Question 21 of 75
What is the modern way to unsubscribe from an Observable when a component is destroyed?
constructor() {
interval(1000).pipe(takeUntilDestroyed()).subscribe((n) => this.tick.set(n));
}- ✓Correct answer:
takeUntilDestroyed()from@angular/core/rxjs-interop, which completes the stream on destroy - 2Nothing is needed: all Observables complete on their own
- 3Call
unsubscribe()insidengOnInit
Explanation
It uses DestroyRef under the hood. Called without arguments it needs an injection context; elsewhere pass a DestroyRef. HTTP requests complete by themselves, but interval, valueChanges and router events don't.