Bird
0
0

What will be logged by the following code?

medium📝 Predict Output Q5 of 15
Angular - RxJS Operators
What will be logged by the following code?
const clicks$ = fromEvent(document, 'click');
clicks$.pipe(
  switchMap(() => interval(1000).pipe(take(3)))
).subscribe(console.log);
AThrows an error because interval is not an Observable
BLogs 0,1,2 once after first click only
CLogs all clicks count without delay
DLogs 0,1,2 every second after each click, cancelling previous intervals
Step-by-Step Solution
Solution:
  1. Step 1: Understand event and interval Observables

    Each click triggers switchMap to start a new interval emitting 0,1,2 every second.
  2. Step 2: Effect of switchMap on multiple clicks

    New clicks cancel previous intervals, so only latest interval emits values.
  3. Final Answer:

    Logs 0,1,2 every second after each click, cancelling previous intervals -> Option D
  4. Quick Check:

    switchMap cancels previous inner Observables = A [OK]
Quick Trick: switchMap cancels previous intervals on new clicks [OK]
Common Mistakes:
MISTAKES
  • Expecting all intervals to run simultaneously
  • Thinking only first interval runs
  • Assuming interval is not an Observable

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes