Skip to content

Instantly share code, notes, and snippets.

@yoonseopshin
Last active December 19, 2021 10:17
Show Gist options
  • Save yoonseopshin/b41cfc95b2e33c2d1717e54eb3620295 to your computer and use it in GitHub Desktop.
Save yoonseopshin/b41cfc95b2e33c2d1717e54eb3620295 to your computer and use it in GitHub Desktop.
Android throttle click extension implementation (for single click)
class OnThrottleClickListener(
private val dispatcher: CoroutineDispatcher,
private val onClickListener: View.OnClickListener,
private val interval: Long,
) : View.OnClickListener {
private var isClickable = true
override fun onClick(view: View) {
if (isClickable) {
isClickable = false
view.findViewTreeLifecycleOwner()?.let { lifecycleOwner ->
lifecycleOwner.lifecycle.coroutineScope.launch(dispatcher) {
onClickListener.onClick(view)
delay(interval)
isClickable = true
}
}
}
}
}
fun View.setOnThrottleClick(
dispatcher: CoroutineDispatcher = Dispatchers.Main,
interval: Long = 500L,
action: (view: View) -> Unit = {}
) {
val listener = View.OnClickListener { action(it) }
setOnClickListener(OnThrottleClickListener(dispatcher, listener, interval))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment