...

/

Using mergeMap and concatMap Functions

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, 1
const emitTreeTwoOne = of(3, 2, 1);
// Create a new observable that delays each emission from emitTreeTwoOne based on its value
const delayedEmit = emitTreeTwoOne.pipe(
mergeMap((value: number) => {
console.log(
`>> emit >>
${new Date().toLocaleTimeString()}
value: ${value},
delaying: ${1000 * value} ms`
);
// Emit the value after a delay
return of(value).pipe(delay(1000 * value))
})
);
  • We have an Observable named emitThreeTwoOne on line 2, which will emit the values 3, then 2, then 1.

  • We then pipe this Observable on line 5 into a mergeMap function that logs the emitted value to the console, along with a timestamp. This function then emits the value received after a delay, using the delay function from the RxJS library.

...