Learn RxJS
Search…
concatMap

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

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

Examples

Example 1: Demonstrating the difference between concatMap and mergeMap
💡 Note the difference between concatMap and mergeMap. Because concatMap does not subscribe to the next observable until the previous completes, the value from the source delayed by 2000ms will be emitted first. Contrast this with mergeMap which subscribes immediately to inner observables, the observable with the lesser delay (1000ms) will emit, followed by the observable which takes 2000ms to complete.
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { concatMap, delay, mergeMap } from 'rxjs/operators';
4
5
//emit delay value
6
const source = of(2000, 1000);
7
// map value from source into inner observable, when complete emit result and move to next
8
const example = source.pipe(
9
concatMap(val => of(`Delayed by: ${val}ms`).pipe(delay(val)))
10
);
11
//output: With concatMap: Delayed by: 2000ms, With concatMap: Delayed by: 1000ms
12
const subscribe = example.subscribe(val =>
13
console.log(`With concatMap: ${val}`)
14
);
15
16
// showing the difference between concatMap and mergeMap
17
const mergeMapExample = source
18
.pipe(
19
// just so we can log this after the first example has run
20
delay(5000),
21
mergeMap(val => of(`Delayed by: ${val}ms`).pipe(delay(val)))
22
)
23
.subscribe(val => console.log(`With mergeMap: ${val}`));
Copied!
Example 2: Map to promise
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { concatMap } from 'rxjs/operators';
4
5
//emit 'Hello' and 'Goodbye'
6
const source = of('Hello', 'Goodbye');
7
//example with promise
8
const examplePromise = val => new Promise(resolve => resolve(`${val} World!`));
9
// map value from source into inner observable, when complete emit result and move to next
10
const example = source.pipe(concatMap(val => examplePromise(val)));
11
//output: 'Example w/ Promise: 'Hello World', Example w/ Promise: 'Goodbye World'
12
const subscribe = example.subscribe(val =>
13
console.log('Example w/ Promise:', val)
14
);
Copied!
Example 3: Supplying a projection function
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { concatMap } from 'rxjs/operators';
4
5
//emit 'Hello' and 'Goodbye'
6
const source = of('Hello', 'Goodbye');
7
//example with promise
8
const examplePromise = val => new Promise(resolve => resolve(`${val} World!`));
9
//result of first param passed to second param selector function before being returned
10
const example = source.pipe(
11
concatMap(
12
val => examplePromise(val),
13
result => `${result} w/ selector!`
14
)
15
);
16
//output: 'Example w/ Selector: 'Hello w/ Selector', Example w/ Selector: 'Goodbye w/ Selector'
17
const subscribe = example.subscribe(val =>
18
console.log('Example w/ Selector:', val)
19
);
Copied!

Additional Resources

Last modified 9mo ago