:bulb: 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.
// RxJS v6+import { of } from'rxjs';import { concatMap, delay, mergeMap } from'rxjs/operators';//emit delay valueconstsource=of(2000,1000);// map value from source into inner observable, when complete emit result and move to nextconstexample=source.pipe(concatMap(val =>of(`Delayed by: ${val}ms`).pipe(delay(val))));//output: With concatMap: Delayed by: 2000ms, With concatMap: Delayed by: 1000msconstsubscribe=example.subscribe(val =>console.log(`With concatMap: ${val}`));// showing the difference between concatMap and mergeMapconstmergeMapExample= source.pipe(// just so we can log this after the first example has rundelay(5000),mergeMap(val =>of(`Delayed by: ${val}ms`).pipe(delay(val))) ).subscribe(val =>console.log(`With mergeMap: ${val}`));
// RxJS v6+import { of } from'rxjs';import { concatMap } from'rxjs/operators';//emit 'Hello' and 'Goodbye'constsource=of('Hello','Goodbye');//example with promiseconstexamplePromise= val =>newPromise(resolve =>resolve(`${val} World!`));// map value from source into inner observable, when complete emit result and move to nextconstexample=source.pipe(concatMap(val =>examplePromise(val)));//output: 'Example w/ Promise: 'Hello World', Example w/ Promise: 'Goodbye World'constsubscribe=example.subscribe(val =>console.log('Example w/ Promise:', val));
// RxJS v6+import { of } from'rxjs';import { concatMap } from'rxjs/operators';//emit 'Hello' and 'Goodbye'constsource=of('Hello','Goodbye');//example with promiseconstexamplePromise= val =>newPromise(resolve =>resolve(`${val} World!`));//result of first param passed to second param selector function before being returnedconstexample=source.pipe(concatMap(val =>examplePromise(val), result =>`${result} w/ selector!`));//output: 'Example w/ Selector: 'Hello w/ Selector', Example w/ Selector: 'Goodbye w/ Selector'constsubscribe=example.subscribe(val =>console.log('Example w/ Selector:', val));