Skip to content

Instantly share code, notes, and snippets.

@deveshmittal
Last active November 11, 2023 13:56
Show Gist options
  • Select an option

  • Save deveshmittal/30842b7e05a17329c96238977d4a168e to your computer and use it in GitHub Desktop.

Select an option

Save deveshmittal/30842b7e05a17329c96238977d4a168e to your computer and use it in GitHub Desktop.
Debounce using coroutines on a view
object ViewExt{
fun View.setDebounceClickListener(
duration: Duration = 300.milliseconds,
action: (View) -> Unit
) {
this.setDebounceClickListener(duration.inWholeMilliseconds, action)
}
private fun View.setDebounceClickListener(
timeInMillis: Long,
action: (View) -> Unit
) {
var debounceJob = AtomicReference<Job?>(null)
val viewScope = findViewTreeLifecycleOwner()?.lifecycleScope ?: CoroutineScope(Dispatchers.Main + SupervisorJob())
setOnClickListener{ view ->
debounceJob.get()?.cancel()
debounceJob.set(viewScope.launch {
delay(timeInMillis)
action(view)
})
}
addOnAttachStateChangeListener(object:View.OnAttachStateChangeListener{
override fun onViewAttachedToWindow(p0: View) {
}
override fun onViewDetachedFromWindow(p0: View) {
debounceJob.get()?.cancel()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment