What's a good way to prevent duplicate clicks of a button in Android Compose?

3.7k Views Asked by At

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?

1

There are 1 best solutions below

3
On

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
   }
}