Throttling All Clicks on Android

By Quentin Colle, Senior Android Engineer

Engineering @ Prolific Interactive
Prolific Interactive
3 min readMar 16, 2018

--

There are a variety of ways you can improve user experience across your Android app. One of the simplest improvements you can make is to prevent a user from inadvertently performing an action twice, or firing multiple events by repeatedly clicking the same button. Imagine the scenario where your user is about to place an order and mistakenly clicks the button to place the order more than once. In this situation, you want to avoid billing the customer multiple times for the same order. Although there are many ways to achieve this, throttling is one of the easiest and most efficient practices.

Rx Binding

In combination with RxJava and RxBinding, throttling has been made easy for us. Simply:

This solution is still painful as you must implement it for every click listener that you want to throttle, and in my case, it turned out to be all of them.

DataBinding

As a solution, we can leverage the DataBinding @BindingAdapter feature so we could override all the clicks by default.

This worked well, but it would be ideal to go a little bit further and dispose of the subscription. Sadly, because the method is static, it is not possible to tie it to anything from the activity or the fragment. We could try to get the context from the view and go up to the parent activity, but it’s not very straightforward. Luckily, DataBinding provides a way to create custom components that contain BindingAdapters for a specific Activity/Fragment.

The component is created this way:

This will generate a DataBindingComponent class that you can extend to make your own implementation.

You can then create it when binding your view:

Lifecycle

Now that we have a class that can implement the DataBindingComponent, we can use the Lifecycle Architecture Component and add the LifecycleComponent as an observer. By doing this, any view can now provide its lifecycle for disposing the subscription. So here is the final LifecycleComponent implementation. Enjoy!

Conclusion

By combining RxBinding, DataBinding and Lifecycle Architecture Component, we get this smooth click throttling on all the views for free while not leaking the view. Hopefully you can make use of it as well.

Shoutout to Erick Chang for pitching the original idea to me, and to Lyla Fujiwara for the final polish using Lifecycle.

--

--

Engineering @ Prolific Interactive
Prolific Interactive

Our team partners with leading brands to create incredible mobile products. Here, we share ideas about engineering, mobile, and tech culture.