Sooner or later every developer comes across a problem with too many function calls in a short amount of time. A perfect example is user mashing the very same button which triggers multiple click events. The most popular solution is to introduce debouncing mechanism, which basically omits any calls in given time after previous invoke.

Image for post

As android platform is quite mature at this point, there are several approaches. For managing click events we can use external libraries or create our own implementation. Unfortunately ready solutions require us to use different api than basic onClickListener.

Databinding

There is a simple trick for those who use databinding. We can override android:onClick to make it use our own debouncing.

BindingAdapters.kt

@BindingAdapter("android:onClick")
fun setDebouncedListener(view: Button, onClickListener: View.OnClickListener) {
    val clickWithDebounce: (view: View) -> Unit = {

        /**
         *   add debounce logic here
         */

        onClickListener.onClick(it)
    }
    view.setOnClickListener(clickWithDebounce)
}

Create binding between activity and layout

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  val binding = DataBindingUtil.setContentView<ActivityMainBinding>(
    this, R.layout.activity_main
  )
binding.activity = this
binding.coroutineScope = lifecycleScope
}

#data-binding #kotlin #android #coroutine

Android Click Debounce
13.85 GEEK