rxjs

Exhaust Map

Exhaust Map

In this tutorial, we will learn about the Exhaust Map operator of RXJS.

 Exhaust Map

Map to inner observable, ignore other values until that observable completes

Suppose we have situations where what we want to do is to ignore new values in the source Observable until the previous value is completely processed we can do this using the Exhaust map operator.

For example, let's say that we are making a backend API request in response to a click in a save button. 

 but what happens now if the user clicks the save button multiple times it will make multiple API calls to the backend, so avoid this we can use Exhaust Map.

Example:

 url = "https://jsonplaceholder.typicode.com/posts/1";

 num = 0;

 @ViewChild("btn", { static: false }) btn: ElementRef;

  fromEvent(this.btn.nativeElement, "click")
      .pipe(
        exhaustMap(() => this.onSave(this.num++))
      )
      .subscribe((res) => {
        console.log(res);
      });

onSave(num) {
    return this.http.put(this.url, { title: num });
  }

The above Example will make a request on a button click but if you click on the button multiple times it will still make only one request or wait for another request to finish.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment