Skip to content

Instantly share code, notes, and snippets.

@kibotu
Last active August 6, 2021 13:05
Show Gist options
  • Save kibotu/d949f8f4c0f095f9118c095b4c272232 to your computer and use it in GitHub Desktop.
Save kibotu/d949f8f4c0f095f9118c095b4c272232 to your computer and use it in GitHub Desktop.
ThrottleFirstClickListener
import android.view.View
/**
* An OnClickListener that sends only the first click of a given Time Interval
*
* @param defaultInterval time frame to skip until next click is send
* @param onThrottleFirstClick callback
*/
class ThrottleFirstClickListener(
private var defaultInterval: Int = 100,
private val onThrottleFirstClick: (View) -> Unit
) : View.OnClickListener {
private var lastTimeClicked: Long = 0
override fun onClick(view: View) {
val currentTime = System.currentTimeMillis()
if (currentTime - lastTimeClicked < defaultInterval) {
return
}
lastTimeClicked = System.currentTimeMillis()
onThrottleFirstClick(view)
}
}
fun View.setOnClickListenerThrottled(defaultInterval: Int = 100, onThrottleFirstClick: (View) -> Unit): ThrottleFirstClickListener {
val throttleFirstClickListener = ThrottleFirstClickListener(defaultInterval = defaultInterval) {
onThrottleFirstClick(it)
}
setOnClickListener(throttleFirstClickListener)
return throttleFirstClickListener
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment