1

Let's say you call the signup API when a button is clicked.

Get the API response and go to the main screen.

In this case the api is called multiple times when the button is pressed repeatedly quickly.

I solved this problem to some extent using Rxjava before using compose.

How can compose solve this problem?

최정현
  • 31
  • 1
  • 5

1 Answers1

1

Generally speaking, this is not necessary as Compose handles button clicks normally and prevents multiple clicks. But if you're using some custom button and for whatever reason are getting multiple clicks, there are a number of solutions. You should however disable your button whenever the api is called and only re-enable it after the api completes.

You can use a click debouncer. It is equivalent to using rxJava but uses a Kotlin flow instead and has a built-in debounce method:

How to disable simultaneous clicks on multiple items in Jetpack Compose List / Column / Row (out of the box debounce?)

or you can just use a variable that acts as a flag to indicate that the api call is already being executed. If any additional clicks occur during the api call, they will be ignored as long as the flag is set. Once the api call is complete, just reset the flag:

class MyViewModel: ViewModel() {
   private apiInUse = false

   fun someApiCall() {
      if (apiInUse) {
         return
      }

      // Make your api call
      apiInUse = true
      myApi()
      apiInUse = false
   }
}
Johann
  • 27,536
  • 39
  • 165
  • 279
  • Smart and easy way, I used to do it by watching the timer with `SystemClock.elapsedRealtime()` if it was too quick the double click before my alert dialog appear it would return... – F.Mysir Jan 11 '22 at 17:19
  • Adding to @Johann, If your button is still visible after submitting an api call, do this: IN UI -> `MyButton(text=text, onClick={ if (vm.apiInUse){ return@MyButton} vm.someApiCall()}` – binrebin Aug 14 '22 at 07:49
  • IMO this is not a duplicate of the other one linked. I think with mutex it looks much cleaner ```class Lockable { val locker = mutex() suspend fun ignoreDuplicateActions(action:suspend ()->T):T? { if (locker.isLocked) return null else withLock { action() } }``` – Suryavel TR Nov 05 '22 at 09:12