switchMap helps you handle changing data streams by switching to the latest one and ignoring old ones. It keeps your app fast and up-to-date without confusion.
switchMap for flattening in Angular
sourceObservable.pipe( switchMap(value => innerObservable) )
switchMap takes a function that returns a new observable.
It unsubscribes from the previous inner observable when a new value arrives.
this.searchInput.valueChanges.pipe( switchMap(term => this.api.search(term)) )
of(1, 2, 3).pipe( switchMap(x => of(x * 10)) ).subscribe(console.log);
This Angular component uses switchMap to handle user input changes. When you type in the input box, it calls fakeApi which simulates a delayed response. If you type quickly, previous calls are cancelled and only the latest result shows.
import { Component } from '@angular/core'; import { FormControl } from '@angular/forms'; import { of } from 'rxjs'; import { delay, switchMap } from 'rxjs/operators'; @Component({ selector: 'app-switchmap-example', template: ` <input [formControl]="searchControl" placeholder="Type to search" aria-label="Search input" /> <p>Result: {{ result }}</p> `, standalone: true }) export class SwitchMapExampleComponent { searchControl = new FormControl(''); result = ''; constructor() { this.searchControl.valueChanges.pipe( switchMap(term => this.fakeApi(term)) ).subscribe(res => this.result = res); } fakeApi(term: string | null) { // Simulate API delay return of(`Result for "${term}"`).pipe(delay(500)); } }
Use switchMap when you want to ignore old inner observables and only keep the latest.
It helps prevent race conditions in asynchronous calls like HTTP requests.
Remember to handle empty or invalid inputs to avoid unnecessary calls.
switchMap switches to the newest inner observable and cancels previous ones.
It is great for handling fast-changing data like user input or live searches.
Helps keep your app responsive and avoids outdated data showing.