DEV Community

Deborah Kurata
Deborah Kurata

Posted on

RxJS Operator: concatMap

The concatMap RxJS Operator is a higher-order mapping operator that processes each emitted value in order and waits for its inner Observable to complete before processing the next item.

For example:

products$ = this.categorySelected$
  .pipe(
       concatMap(catId=>
            this.http.get<Product[]>(`${this.url}?cat=${catId}`))
  );

Enter fullscreen mode Exit fullscreen mode

In the above code, the concatMap will perform the HTTP get and wait for the response before processing the next item emitted from this.categorySelected$.

How Does concatMap Work?

We can think of the concatMap like a relay race: the next runner can't start until the prior runner completes. And the runners cannot run out of sequence.

image

Let's look at an Example

image
In this example, the user clicks the category with an id of 2, changes their mind and picks 3, then decides they really want category 1.

Following the numbers on the screen shot above:

  • The concatMap issues a get request for category 2,
  • waits for the response,
  • then issues a get request for category 3,
  • waits for the response,
  • then issues a get request for category 1,
  • and waits for the response.

For this specific example, where the user can change their mind on the selected category, using concatMap doesn't make sense. It takes too long for each selection to be processed and returns results that are no longer needed.

When Should We Use concatMap?

The concatMap is great for things like updates or deletes where you want to ensure that each request completes before the next one begins.

It's also great any time that the request/response order matters.

Top comments (0)