--

Debounce for android button clicks via bindingAdapter

@BindingAdapter("android:onClick")
fun setDebounceListener(view: Button, onClickListener: View.OnClickListener) {
val scope = ViewTreeLifecycleOwner.get(view)!!.lifecycleScope
val clickWithDebounce: (view: View) -> Unit =
debounce(scope = scope) {
onClickListener.onClick(it)
}

view.setOnClickListener(clickWithDebounce)
}


fun <T> debounce(
delayMillis: Long = 300L,
scope: CoroutineScope,
action: (T) -> Unit
): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
if (debounceJob == null) {
debounceJob = scope.launch {
action(param)
delay(delayMillis)
debounceJob = null
}
}
}
}

Usage :

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{ () -> activity.youOnClickCallbackHere()}"
android:text="Click with debounce" />

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Balwinder Singh Rajput
Balwinder Singh Rajput

Written by Balwinder Singh Rajput

Hi there πŸ‘‹ Namaste πŸ™πŸ» .πŸ‘¨β€πŸ’» developing apps from 12+ years. πŸ‘¨β€πŸ« IoT | E-commerce | baking domain expert.

No responses yet

Write a response