Home > front end >  concatMap vs. switchMap when observable only returns one value in Angular
concatMap vs. switchMap when observable only returns one value in Angular

Time:10-15

I get the difference between concatMap and switchMap when an observable returns more than one value. However when all observables just return a single value, is there any advantage to using one over the other? Here is an example with the exact same call in the constructor, one using concatMap and one using switchMap. Is either preferred over the other in this case?

import { Component } from '@angular/core';
import { concatMap, forkJoin, Observable, of, switchMap } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  var1: any[];
  var2: any[];
  detailVar: any;


  func1(): Observable<any[]> {
    return of([
      { id: 1, value: 'One' },
      { id: 2, value: 'Two' },
      { id: 3, value: 'Three' }
    ])
  }

  func2(): Observable<any[]> {
    return of([
      { id: 4, value: 'Four' },
      { id: 5, value: 'Five' },
      { id: 6, value: 'Six' }
    ])
  }

  funcDetail(): Observable<any> {
    return of(
      { id: 1, name: 'name', oneId: 2, twoId: 5 }
    )
  }

  constructor() {

    // concatMap


    this.funcDetail().pipe(concatMap((data) => {
      this.detailVar = data;
      return forkJoin([
        this.func1(),
        this.func2()
      ])
    }
    )).subscribe((dds) => {
      this.var1 = dds[0];
      this.var2 = dds[1];

      console.log(this.detailVar);
      console.log(this.var1);
      console.log(this.var2);
    });


    // switchMap

    this.funcDetail().pipe(switchMap((data) => {
      this.detailVar = data;
      return forkJoin([
        this.func1(),
        this.func2()
      ])
    }
    )).subscribe((dds) => {
      this.var1 = dds[0];
      this.var2 = dds[1];

      console.log(this.detailVar);
      console.log(this.var1);
      console.log(this.var2);
    });


  }


}

CodePudding user response:

The difference is if the source Observable emits before the merged Observable emits and completes.

With switchMap it unsubscribes, while with concatMap it'll wait until the merged Observable completes.

But if you know that for example the source Observable is synchronous and emits always only once (like of(1)) then from the functional perspective there's no difference if you use mergeMap, switchMap or concatMap.

  • Related