← Back to list

Understanding switchMap and mergeMap in Angular: A Detailed Explanation

In Angular, rxjs operators like switchMap and mergeMap are commonly used for handling asynchronous operations, such as HTTP requests or…

Neelam S · 2024-12-24 15:35 · 0 claps · 3.5 min read paywalled
#switchmap #mergemap #rxjs #typescript #javascript
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Understanding switchMap and mergeMap in Angular: A Detailed Explanation

In Angular, rxjs operators like switchMap and mergeMap are commonly used for handling asynchronous operations, such as HTTP requests or user input changes. While both operators deal with observables, they behave differently and are suited for different scenarios.

we will explore the difference between switchMap and mergeMap, explain when to use them, and provide examples to help you understand their behavior in real-world Angular applications.

Scenario: Angular Application Setup

Imagine we are building a simple Angular application with a search feature. The user types a query into an input box, and based on their input, we want to filter a list of fruits.

To simulate the behavior of asynchronous operations like API calls, we’ll create a function that returns an observable with a delay. As the user types, we want to filter the fruits, but the main challenge is deciding how we should handle the request when the user types quickly (i.e., multiple requests being triggered in a short amount of time).

We’ll use mergeMap and switchMap to see the difference in how they handle these requests.

The Angular Setup: Components and Logic

HTML Template:

<div>
  <h1>RxJS: switchMap vs mergeMap</h1>
  <input type="text" [formControl]="searchControl" placeholder="Search fruits" />
  <div *ngIf="loading">Loading...</div>
  <ul *ngIf="fruits.length">
    <li *ngFor="let fruit of fruits">{{ fruit }}</li>
  </ul>
</div>

Component Logic (TypeScript):

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { debounceTime, switchMap, mergeMap } from 'rxjs';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  fruits = [];
  searchControl = new FormControl('');
  loading = false;
  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        debounceTime(500),  // Wait for the user to stop typing
        // Uncomment one of the following to test `mergeMap` or `switchMap`:
        // mergeMap((query) => this.fetchFruits(query)),  // For mergeMap
        switchMap((query) => this.fetchFruits(query))  // For switchMap
      )
      .subscribe((response) => {
        this.fruits = response;
        this.loading = false;
      });
    this.searchControl.valueChanges.subscribe(() => {
      this.loading = true;  // Show the loading spinner when typing
    });
  }
  fetchFruits(query: string): Observable<string[]> {
    return new Observable((observer) => {
      setTimeout(() => {
        if (query.toLowerCase().includes('a')) {
          observer.next(['Apple', 'Pineapple']);
        } else {
          observer.next(['Mango', 'Orange']);
        }
        observer.complete();
      }, 2000);  // Simulate a delay
    });
  }
}

Key RxJS Operators: mergeMap and switchMap

1. mergeMap

The mergeMap operator allows you to handle multiple asynchronous requests simultaneously. If a new request is triggered while the previous one is still in progress, mergeMap will continue processing all of them and return results as soon as each one completes.

Behavior of mergeMap:

  • If the user types quickly, multiple requests are made and processed one by one.
  • The results from each request are emitted in the order they finish.

Example Behavior:

  • If the user types “a”, it starts waiting for a response.
  • When the user types “pp”, it triggers a second request (and the first request is still processing).
  • After the second request completes, the first request result will appear, followed by the second one.

This might not be ideal in certain scenarios, as it can lead to unnecessary or redundant data being processed.

When to Use mergeMap:

  • When you need to process all requests, regardless of when they were triggered.
  • For scenarios like batch processing, where all incoming events (requests) should be processed.

2. switchMap

The switchMap operator cancels the previous request when a new one is triggered. It only processes the most recent request and discards any earlier ones that haven't completed yet.

Behavior of switchMap:

  • If the user types quickly, only the last request will be processed.
  • The previous requests are canceled in favor of the new request.

Example Behavior:

  • When the user types “a”, it starts waiting for a response.
  • If the user then types “pp”, it cancels the first request and sends a new request.
  • The result of the new query (“pp”) is returned, and the first query’s result is ignored.

This behavior is ideal when you want to focus only on the latest request, such as in search and filtering operations.

When to Use switchMap:

  • When you want to cancel previous requests in favor of the latest one.
  • For real-time search or filtering, where only the most recent query matters.

Practical Example: Real-time Search

Let’s look at two different use cases for real-time search, using both mergeMap and switchMap.

Example 1: Using mergeMap

this.searchControl.valueChanges
  .pipe(
    debounceTime(500),
    mergeMap((query) => this.fetchFruits(query))
  )
  .subscribe((response) => {
    this.fruits = response;
    this.loading = false;
  });

With this approach, multiple results will be shown as the user types, and all requests will be processed.

Example 2: Using switchMap

this.searchControl.valueChanges
  .pipe(
    debounceTime(500),
    switchMap((query) => this.fetchFruits(query))
  )
  .subscribe((response) => {
    this.fruits = response;
    this.loading = false;
  });

Here, only the final result is processed. Even if the user types quickly, previous requests will be canceled, and only the most recent query will be shown.

Conclusion

Understanding the differences between mergeMap and switchMap is crucial for handling asynchronous operations efficiently in Angular. By choosing the right operator based on your use case, you can ensure a better user experience, especially in scenarios like real-time search or batch processing.

  • Use **mergeMap** when you need to process all requests regardless of the order.
  • Use **switchMap** when you only care about the most recent request, especially in real-time search applications.

메타데이터
post_id
da8d3fced3c8
slug
understanding-switchmap-and-mergemap-in-angular-a-detailed-explanation-da8d3fced3c8
url
https://medium.com/@neelamudiya/understanding-switchmap-and-mergemap-in-angular-a-detailed-explanation-da8d3fced3c8
canonical_url
https://medium.com/@neelamudiya/understanding-switchmap-and-mergemap-in-angular-a-detailed-explanation-da8d3fced3c8
author_url
https://medium.com/@neelamudiya
status
ok
fetched_at
2026-09-04 21:40:00