concatMap

signature: concatMap(project: function, resultSelector: function): Observable

Map values to inner observable, subscribe and emit in order.

Examples

Example 1: Map to inner observable

( jsBin | jsFiddle )

import { of } from 'rxjs/observable/of';
import { concatMap } from 'rxjs/operators';

//emit 'Hello' and 'Goodbye'
const source = of('Hello', 'Goodbye');
// map value from source into inner observable, when complete emit result and move to next
const example = source.pipe(concatMap(val => of(`${val} World!`)));
//output: 'Example One: 'Hello World', Example One: 'Goodbye World'
const subscribe = example.subscribe(val => console.log('Example One:', val));
Example 2: Map to promise

( jsBin | jsFiddle )

import { of } from 'rxjs/observable/of';
import { concatMap } from 'rxjs/operators';

//emit 'Hello' and 'Goodbye'
const source = of('Hello', 'Goodbye');
//example with promise
const examplePromise = val => new Promise(resolve => resolve(`${val} World!`));
// map value from source into inner observable, when complete emit result and move to next
const example = source.pipe(concatMap(val => examplePromise(val)));
//output: 'Example w/ Promise: 'Hello World', Example w/ Promise: 'Goodbye World'
const subscribe = example.subscribe(val =>
  console.log('Example w/ Promise:', val)
);
Example 3: Supplying a projection function

( jsBin | jsFiddle )

import { of } from 'rxjs/observable/of';
import { concatMap } from 'rxjs/operators';

//emit 'Hello' and 'Goodbye'
const source = of('Hello', 'Goodbye');
//example with promise
const examplePromise = val => new Promise(resolve => resolve(`${val} World!`));
//result of first param passed to second param selector function before being  returned
const example = source.pipe(
  concatMap(
    val => examplePromise(val),
    result => `${result} w/ selector!`
  )
);
//output: 'Example w/ Selector: 'Hello w/ Selector', Example w/ Selector: 'Goodbye w/ Selector'
const subscribe = example.subscribe(val =>
  console.log('Example w/ Selector:', val)
);
Example 4: Illustrating difference between concatMap and mergeMap

( jsBin | jsFiddle )

import { of } from 'rxjs/observable/of';
import { buffer } from 'rxjs/operators';

const concatMapSub = of(2000, 1000)
  .pipe(
   concatMap(v => of(v).pipe(delay(v)))
  )
  // concatMap: 2000, concatMap: 1000
  .subscribe(v => console.log('concatMap:', v));

const mergeMapSub = of(2000, 1000)
  .pipe(
    mergeMap(v => of(v).pipe(delay(v)))
  )
  // mergeMap: 1000, mergeMap: 2000
  .subscribe(v => console.log('mergeMap:', v));

Additional Resources


:file_folder: Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/patching/operator/concatMap.ts

results matching ""

    No results matching ""