Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created June 12, 2019 18:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afollestad/a13ef2fbd5c5540cb2a7d6918eaabdcd to your computer and use it in GitHub Desktop.
Save afollestad/a13ef2fbd5c5540cb2a7d6918eaabdcd to your computer and use it in GitHub Desktop.
Debounce clicks in Kotlin
import android.view.View
internal object Debouncer {
@Volatile private var enabled: Boolean = true
private val enableAgain = Runnable { enabled = true }
fun canPerform(view: View): Boolean {
if (enabled) {
enabled = false
view.post(enableAgain)
return true
}
return false
}
}
internal fun <T : View> T.onClickDebounced(click: (view: T) -> Unit) {
setOnClickListener {
if (Debouncer.canPerform(it)) {
@Suppress("UNCHECKED_CAST")
click(it as T)
}
}
}
@denebchorny
Copy link

Could you give me a use example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment