Using mergeMap and concatMap Functions
Learn how to use mergeMap and concatMap functions to process emitted values from Observables in or out of order.
Observable emits out of order
When an Observable emits values, the values emitted may arrive at a subscriber out of order.
Let’s assume that an Observable takes three seconds to emit a single value, and then two seconds to emit another value, and finally, one second to emit the third value.
This can be simulated as follows:
Press + to interact
// Create an observable that emits values 3, 2, 1const emitTreeTwoOne = of(3, 2, 1);// Create a new observable that delays each emission from emitTreeTwoOne based on its valueconst delayedEmit = emitTreeTwoOne.pipe(mergeMap((value: number) => {console.log(`>> emit >>${new Date().toLocaleTimeString()}value: ${value},delaying: ${1000 * value} ms`);// Emit the value after a delayreturn of(value).pipe(delay(1000 * value))}));
-
We have an Observable named
emitThreeTwoOne
on line 2, which will emit the values3
, then2
, then1
. -
We then
pipe
this Observable on line 5 into amergeMap
function that logs the emitted value to the console, along with a timestamp. This function then emits the value received after a delay, using thedelay
function from the RxJS library.
...