L. Kvri
L. Kvri

Reputation: 1723

RxJs how to take multiple click last event?

How can I take the last click event with RxJS to prevent multiple API calls of each button click? I have a mechanism where exists the next button which increments a clientSlot #. If the user clicked on the next button with normal speed get the next client slot data one after another. But if the user clicked fast one after another multiple times I would not want to display only the at last because it wasted time calling the APIs. because the user is unable to follow the data changes on the screen, I would like to show the latest click triggered data based on the last incremented clientSlot #.

With debouncTime usage I able to implement it, but without debounceTime usage is it possible to implement?

Thank you in advance.

Upvotes: 0

Views: 590

Answers (1)

Bartłomiej Stasiak
Bartłomiej Stasiak

Reputation: 518

Let use switchMap for it - it will cancel unnecessary API requests

Example:

const yourHttpRequest$ = new Subject<InputApiData>();
const yourHttpResponse$: Observable<ClientData> = yourHttpRequest$.pipe(switchMap(
  inputApiData => this.httpService.getClientData(inputApiData)));
yourHttpResponse$.subscribe(clientData => { 
  // your logic to execute after API call was done
  });
yourHttpRequest$.next(inputApiData); // calling API

You have two buttons, which trigger API call. You can place API call in click event handler.

Upvotes: 2

Related Questions