0
0
Angularframework~5 mins

switchMap for flattening in Angular

Choose your learning style9 modes available
Introduction

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.

When you want to cancel previous requests if a new one starts, like searching as you type.
When you have a stream that triggers another stream and only want the latest result.
When handling user input that changes quickly and you want to avoid outdated data.
When you want to flatten nested streams into a single stream for easier handling.
Syntax
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.

Examples
Switches to a new search API call each time the input changes, cancelling the old one.
Angular
this.searchInput.valueChanges.pipe(
  switchMap(term => this.api.search(term))
)
Transforms each number by multiplying by 10 and emits the latest result.
Angular
of(1, 2, 3).pipe(
  switchMap(x => of(x * 10))
).subscribe(console.log);
Sample Program

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.

Angular
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));
  }
}
OutputSuccess
Important Notes

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.

Summary

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.