Bird
Raised Fist0
Angularframework~20 mins

switchMap for flattening in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
SwitchMap Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Angular component output when clicking the button twice quickly?

Consider this Angular component using switchMap to handle button clicks:

import { Component } from '@angular/core';
import { Subject, of } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-switchmap-demo',
  template: `
    
    

{{message}}

` }) export class SwitchMapDemoComponent { clicks = new Subject(); message = ''; constructor() { this.clicks.pipe( switchMap(() => of('Response').pipe(delay(1000))) ).subscribe(res => this.message = res); } }

What will the message show after clicking the button twice quickly (within less than 1 second)?

Angular
import { Component } from '@angular/core';
import { Subject, of } from 'rxjs';
import { delay, switchMap } from 'rxjs/operators';

@Component({
  selector: 'app-switchmap-demo',
  template: `
    <button (click)="clicks.next()">Click me</button>
    <p>{{message}}</p>
  `
})
export class SwitchMapDemoComponent {
  clicks = new Subject<void>();
  message = '';

  constructor() {
    this.clicks.pipe(
      switchMap(() => of('Response').pipe(delay(1000)))
    ).subscribe(res => this.message = res);
  }
}
AThe message updates once after 1 second with 'Response'.
BThe message updates twice, once per click, each after 1 second.
CThe message never updates because the second click cancels the first.
DThe message updates immediately with 'Response' on each click.
Attempts:
2 left
💡 Hint

Think about how switchMap cancels previous inner observables when a new one starts.

📝 Syntax
intermediate
2:00remaining
Which option correctly uses switchMap to flatten HTTP requests in Angular?

You want to use switchMap to flatten a user ID stream into HTTP requests fetching user details. Which code snippet is correct?

AuserId$.pipe(switchMap(id => this.http.get(`/api/users/${id}`)))
BuserId$.pipe(switchMap(id => this.http.get(`/api/users/${id}`)))()
CuserId$.pipe(switchMap(id => this.http.get(`/api/users/${id}`)).subscribe())
DuserId$.pipe(switchMap(id => this.http.get(`/api/users/${id}`)).toPromise())
Attempts:
2 left
💡 Hint

Remember that switchMap expects a function returning an observable.

🔧 Debug
advanced
2:00remaining
Why does this switchMap code never emit values?

Look at this Angular code snippet:

this.source$.pipe(
  switchMap(() => {
    // Missing return statement
    of('Hello');
  })
).subscribe(console.log);

Why does it never print anything?

Angular
this.source$.pipe(
  switchMap(() => {
    // Missing return statement
    of('Hello');
  })
).subscribe(console.log);
ABecause switchMap requires a promise, not an observable.
BBecause the inner function does not return the observable, so switchMap receives undefined.
CBecause of('Hello') is not a valid observable.
DBecause subscribe is missing a next handler.
Attempts:
2 left
💡 Hint

Check if the function inside switchMap returns anything.

❓ state_output
advanced
2:00remaining
What is the final value of data after this switchMap chain?

Given this Angular RxJS code:

let data = '';

const clicks = new Subject();

clicks.pipe(
  switchMap(id => of(`User${id}`).pipe(delay(500)))
).subscribe(value => data = value);

clicks.next(1);
setTimeout(() => clicks.next(2), 200);
setTimeout(() => clicks.next(3), 800);
setTimeout(() => console.log(data), 1500);

What will be logged to the console?

Angular
let data = '';

const clicks = new Subject<number>();

clicks.pipe(
  switchMap(id => of(`User${id}`).pipe(delay(500)))
).subscribe(value => data = value);

clicks.next(1);
setTimeout(() => clicks.next(2), 200);
setTimeout(() => clicks.next(3), 800);
setTimeout(() => console.log(data), 1500);
A'User2'
B'User1'
C'User3'
D'' (empty string)
Attempts:
2 left
💡 Hint

Remember that switchMap cancels previous inner observables when a new value arrives.

🧠 Conceptual
expert
2:00remaining
Why is switchMap preferred over mergeMap for flattening HTTP requests in Angular forms?

In Angular reactive forms, when reacting to user input to fetch data, why is switchMap often preferred over mergeMap?

ABecause mergeMap only allows one inner observable at a time.
BBecause switchMap queues all requests and emits results in order.
CBecause mergeMap cancels previous requests automatically.
DBecause switchMap cancels previous HTTP requests, preventing outdated data from arriving.
Attempts:
2 left
💡 Hint

Think about what happens if the user types quickly and multiple HTTP requests start.

Practice

(1/5)
1. What is the main purpose of switchMap in Angular RxJS?
easy
A. To combine multiple observables into one without canceling
B. To switch to the latest inner observable and cancel previous ones
C. To delay the emission of values by a fixed time
D. To filter values based on a condition

Solution

  1. Step 1: Understand the behavior of switchMap

    switchMap listens to an outer observable and switches to a new inner observable each time the outer emits, canceling the previous inner observable.
  2. Step 2: Compare with other operators

    Unlike operators that combine or delay, switchMap cancels previous inner observables to avoid outdated data.
  3. Final Answer:

    To switch to the latest inner observable and cancel previous ones -> Option B
  4. Quick Check:

    switchMap = switch to latest and cancel old [OK]
Hint: Remember: switchMap cancels old streams, keeps newest only [OK]
Common Mistakes:
  • Confusing switchMap with mergeMap which merges all observables
  • Thinking switchMap delays values instead of switching
  • Assuming switchMap filters values directly
2. Which of the following is the correct syntax to use switchMap in an Angular service?
easy
A. observable$.pipe(switchMap(value => http.get(url)))
B. observable$.switchMap(value => http.get(url))
C. switchMap(observable$, value => http.get(url))
D. observable$.map(switchMap(value => http.get(url)))

Solution

  1. Step 1: Recall RxJS pipe syntax

    In Angular, operators like switchMap are used inside the pipe() method on observables.
  2. Step 2: Check each option

    observable$.pipe(switchMap(value => http.get(url))) correctly uses observable$.pipe(switchMap(...)). observable$.switchMap(value => http.get(url)) is invalid because switchMap is not a method on observable directly. switchMap(observable$, value => http.get(url)) has wrong argument order. observable$.map(switchMap(value => http.get(url))) misuses map.
  3. Final Answer:

    observable$.pipe(switchMap(value => http.get(url))) -> Option A
  4. Quick Check:

    Use pipe() with switchMap inside [OK]
Hint: Use pipe() to chain switchMap, not direct method call [OK]
Common Mistakes:
  • Calling switchMap directly on observable without pipe
  • Mixing switchMap with map incorrectly
  • Passing wrong arguments to switchMap
3. Given the code below, what will be logged to the console?
const source$ = of('A', 'B', 'C');
source$.pipe(
  switchMap(letter => of(letter + '1', letter + '2'))
).subscribe(console.log);
medium
A. "C1" and "C2" only
B. ["A1", "A2", "B1", "B2", "C1", "C2"]
C. "A1" and "A2" only
D. Error: switchMap requires an observable

Solution

  1. Step 1: Understand source observable emissions

    The source$ emits 'A', then 'B', then 'C' synchronously.
  2. Step 2: Apply switchMap to each emission

    For each letter, switchMap maps to an observable emitting letter+'1' and letter+'2'. Since source$ emits synchronously, switchMap cancels previous inner observables when a new outer emission occurs, so only the last inner observable's values "C1" and "C2" are emitted.
  3. Step 3: Resulting output

    Only "C1" and "C2" are logged to the console.
  4. Final Answer:

    "C1" and "C2" only -> Option A
  5. Quick Check:

    switchMap cancels previous inner observables, so only last inner observable outputs [OK]
Hint: switchMap cancels previous inner observables, outputs only latest inner values [OK]
Common Mistakes:
  • Thinking switchMap flattens all inner observables in order
  • Expecting all inner observable outputs
  • Confusing switchMap with mergeMap behavior
4. Identify the error in this Angular RxJS code using switchMap:
this.searchTerm$.switchMap(term => this.http.get(`/api/search?q=${term}`))
  .subscribe(results => this.results = results);
medium
A. subscribe callback syntax is incorrect
B. http.get should be replaced with http.post
C. switchMap is used without pipe()
D. searchTerm$ should be a Subject, not Observable

Solution

  1. Step 1: Check usage of switchMap

    In Angular RxJS, operators like switchMap must be used inside the pipe() method, not called directly on the observable.
  2. Step 2: Verify other parts

    http.get usage is valid for GET requests. subscribe callback syntax is correct. searchTerm$ can be any observable.
  3. Final Answer:

    switchMap is used without pipe() -> Option C
  4. Quick Check:

    Operators need pipe() to work [OK]
Hint: Always use pipe() to apply switchMap on observables [OK]
Common Mistakes:
  • Calling switchMap directly on observable
  • Confusing http.get with http.post
  • Miswriting subscribe callback
5. You want to implement a live search input in Angular that cancels previous HTTP requests when the user types fast. Which RxJS operator should you use and why? searchTerm$.pipe( /* what operator here? */ )
hard
A. mergeMap, because it merges all requests and shows all results
B. exhaustMap, because it ignores new requests while one is active
C. concatMap, because it queues requests and processes them one by one
D. switchMap, because it cancels previous requests and uses only the latest

Solution

  1. Step 1: Understand live search requirements

    Live search needs to cancel previous HTTP requests if the user types again quickly to avoid outdated results.
  2. Step 2: Match operator behavior

    switchMap cancels previous inner observables (HTTP requests) and switches to the latest, perfect for live search. mergeMap merges all requests, concatMap queues them, exhaustMap ignores new while active.
  3. Final Answer:

    switchMap, because it cancels previous requests and uses only the latest -> Option D
  4. Quick Check:

    Live search = switchMap cancels old requests [OK]
Hint: Use switchMap to cancel old HTTP calls on new input [OK]
Common Mistakes:
  • Using mergeMap causing multiple overlapping requests
  • Using concatMap causing delayed responses
  • Using exhaustMap ignoring new inputs
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