0
0
Angularframework~20 mins

switchMap for flattening in Angular - Practice Problems & Coding Challenges

Choose your learning style9 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.