ExhaustMap

Projects each source value to an Observable which is merged in the output Observable only if the previous projected Observable has completed.

Explanation:

Basically this exhaustMap operator ignores every new projected Observable if the previous projected Observable has not yet completed. Once that one completes, it will accept and flatten the next projected Observable and repeat this process. This can prevent clicking many times the same button.

Returns an Observable that emits items based on applying a function that you supply to each item emitted by the source Observable, where that function returns a (so-called "inner") Observable. When it projects a source value to an Observable, the output Observable begins emitting the items emitted by that projected Observable. However, exhaustMap ignores every new projected Observable if the previous projected Observable has not yet completed. Once that one completes, it will accept and flatten the next projected Observable and repeat this process.

import { fromEvent, interval } from 'rxjs';
import { exhaustMap, take } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const result = clicks.pipe(
  exhaustMap(ev => interval(1000).pipe(take(5)))
);
result.subscribe(x => console.log(x));

Also, the exhaustMap will help us to avoid multi clicking to a button. Check the following example:

@ViewChild('saveButton') saveButtom: ElementRef;
// Here we make reference to the HTML button
<button #saveButton class="myButtom">
  Save information
</button>
ngAfterViewInit(): void {
  fromEvent(this.saveButtom.nativeElement, 'click')
    .pipe(
      exhaustMap(() => this.saveCourse(1, 'Hello')
      )
    ).subscribe();
}

Last updated