How to prevent multiple clicks in Android Jetpack Compose

Alexander Shevelev
2 min readFeb 12, 2022

--

Sometimes a user of your app may be a “monkey.” Funny, right? It is only a term, and what does it mean you can find here. But in simple words, “monkey” is a user who provides a random input — clicks, gestures, shakes, etc.

The most common example of “monkey” behavior is when someone clicks several times on a clickable item. There can be so many reasons for it — slowness of the Internet connection; the user can be in a hurry or nervous.

As developers, we really like to get a universal solution how to prevent multiple clicks one and for all. Several months ago, there was a discussion on Stackoverflow, in which some answers to the problem were provided. I offered my solutions as well. In this post, I would like to show you my solution to the problem and a solution from my colleague (frankly speaking, it’s far more elegant, simple and robust than mine).

The first solution

The first solution is based on Kotlin coroutines, and it is pretty straightforward. Here is the source code:

In this solution, I create a SharedFlow instance (line 10), put our events into it (line 20), and process them using debounce operator (line 28). So, this algorithm invokes the very last click and cuts the rest.

You can convert this code to a modifier, like so:

Or use it as a wrapper around composable code:

What can I say about this approach? It works. But…

The second solution

…several days ago, my colleague offered another one — far more elegant, robust, and simple. Let’s see the code:

Instead of coroutines, this solution is based on moments of time comparison. All of the magic happens in line 17 — two moments are compared here— for the last event and the previous one. If the difference is greater than some threshold, an event is invoked. Unlike the first one, this algorithm invokes the very first event and cuts the rest.

And of course, you can transform this code to a modifier, like so:

Conclusion

Thus, in this post, I presented you with two completely different approaches to cutting multiple clicks. Which one to choose is up to you. Frankly speaking, I would select the second one if I were you.

--

--

Alexander Shevelev
Alexander Shevelev

Written by Alexander Shevelev

An Android developer from Yandex LLC, Moscow, Russia. That’s all.

Responses (8)