Search⌘ K
AI Features

Using mergeMap and concatMap Functions

Explore how mergeMap and concatMap work in RxJS to transform and manage data streams. Understand how these operators handle values emitted by Observables, with mergeMap allowing out-of-order emissions and concatMap ensuring ordered processing by waiting for each Observable to complete before proceeding.

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:

C++
// 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.

...