Search code examples
rx-javarxjsreactive-programmingrx-swiftreactivex

Prevent multiple api calls


How Can I prevent multiple long api calls (e.g. user tap the button several times) without saving state (e.g. saving state to "isLoading" property).


Solution

  • There are missing requirements here, but assuming you want to avoid making additional calls while there's one executing, until request is finish, you can use take(1) with repeat() and optionally also retry(), take(1) will limit emission to the first click, repeat() will resubscribe again when onComplete() - which ,means the network request done, so you will able to receive single click again and perform request. you can consider also retry() for resubscribing with failure (that will not repeat the request, but will make request available again when clicked)

    getClicksEvents()
      .take(1)
      .flatMap(aVoid -> getRequestObservable())
      .repeat()
      .retry()
      .subscribe( result -> //do your thing );