Last active
October 17, 2019 11:11
-
-
Save gilgoldzweig/c1b499de8d123ed7da9a34f932a731f0 to your computer and use it in GitHub Desktop.
ClickDebouncer.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Handler | |
import android.view.View | |
/** | |
* A class for debouncing clicks | |
*/ | |
abstract class DebouncingOnClickListener : View.OnClickListener { | |
private val clickDebouncer = ClickDebouncer() | |
override fun onClick(v: View) { | |
clickDebouncer.debounceClick { | |
doClick(v) | |
} | |
} | |
abstract fun doClick(v: View) | |
} | |
class ClickDebouncer { | |
private var enabled = true | |
private val handler = Handler() | |
fun debounceClick(onClick: () -> Unit) { | |
if (enabled) { | |
enabled = false | |
handler.postDelayed({ enabled = true }, DEBOUNCE_TIMEOUT) | |
onClick() | |
} | |
} | |
companion object { | |
private const val DEBOUNCE_TIMEOUT = 500L | |
} | |
} | |
inline fun View.debounceClick(crossinline onClick: (view: View) -> Unit) { | |
setOnClickListener(object : DebouncingOnClickListener() { | |
override fun doClick(v: View) { | |
onClick.invoke(v) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment