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)?
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); } }
Think about how switchMap cancels previous inner observables when a new one starts.
switchMap cancels the previous inner observable when a new value arrives. Clicking twice quickly starts two inner observables, but the first is canceled before it emits. Only the last inner observable completes and updates the message once after 1 second.
You want to use switchMap to flatten a user ID stream into HTTP requests fetching user details. Which code snippet is correct?
Remember that switchMap expects a function returning an observable.
Option A correctly returns an observable inside switchMap. Option A incorrectly calls subscribe() inside the pipe, which is invalid. Option A tries to call the result as a function, causing an error. Option A calls toPromise() inside the pipe, which is not valid RxJS usage.
Look at this Angular code snippet:
this.source$.pipe(
switchMap(() => {
// Missing return statement
of('Hello');
})
).subscribe(console.log);Why does it never print anything?
this.source$.pipe( switchMap(() => { // Missing return statement of('Hello'); }) ).subscribe(console.log);
Check if the function inside switchMap returns anything.
The function inside switchMap must return an observable. Here, of('Hello') is created but not returned, so switchMap gets undefined and never emits.
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?
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);
Remember that switchMap cancels previous inner observables when a new value arrives.
Click 1 starts an inner observable delayed 500ms. At 200ms, click 2 starts a new inner observable, canceling the first. At 800ms, click 3 starts another inner observable, canceling the second. The last inner observable emits at 1300ms (800 + 500). So at 1500ms, data is 'User3'.
In Angular reactive forms, when reacting to user input to fetch data, why is switchMap often preferred over mergeMap?
Think about what happens if the user types quickly and multiple HTTP requests start.
switchMap cancels previous inner observables when a new one starts, so only the latest HTTP request result is used. This avoids showing outdated data if earlier requests finish after later ones. mergeMap runs all requests concurrently and emits all results, which can cause race conditions.