DEV Community

diptee
diptee

Posted on

Angular : RxJS concatMap operator

  • In Angular, we use HTTP to get data from backend,HTTP methods always return an observable.Generally we subscribe to that observable and assign response data to class variables to use it in our component.
  • But using RxJS operators we can compose multiple observables(data streams) or process observable data before subscribing to it.

RxJS concatMap operator
It is a High-order Mapping operator an operator that takes value from an outer observable and maps it into inner observable instead of plain values(Observable emits observable).

concatMap operator

  1. Takes each value from the outer observable and maps that value to observable(called as inner observable)
  2. Concat all inner observables into a single observable in order and subscribe to inner observables and emit data of each inner observable into output observable in sequential manner.
  3. concatMap never subscribes to the next inner observable until the previous one completes.

Example:
Display first 3 toppers of the computer department on UI with ROLL NUMBER & MARKS.
toppers

Run live

Here we have 2 API’s
1.First API to get roll numbers of first 3 toppers.
2.Second API to get marks of topper taking roll number as input.

In the above case we need to take all roll numbers from the first API and pass it to the second API.
Normally in such scenarios developers use a nested subscription approach.
Nested
Here due to nested subscription approach output may vary,because we are hitting HTTP requests for each roll number,but here HTTP requests are not completing in sequential manner,depending upon which request completes first that request response data gets pushed in toppersList_1.

So solution to this problem is use concatMap RxJS operator instead of nested subscription.
For given use-case,we need to use two concatMap operator.
concat

First contactMap operator -
getToppers_rollNum() this method returns an Observable of type number[] , conactMap maps Observable<number[]> to Observable <number>(inner observable) then subscribes to inner observable and emit data into output observable(top_3_rollNum$).

Second concatMap operator -
Let's consider top_3_rollNum$ as outer observable.concatMap takes each roll number from the outer observable and hits http request sequentially(here we have 3 inner observables return by 3 http requests) & emits http response data into output observable(topper_marks$).

concatMap never hits the next http request until the previous one completes.

Shorthand syntax for above code
Shorthand

So,concatMap is used where sequence of execution matters.

Thanks for reading! If you found this helpful please share!

Top comments (0)