Skip to content

Instantly share code, notes, and snippets.

@josebraz
Last active July 12, 2022 21:38
Show Gist options
  • Save josebraz/8cc302511d8b240400f6e6f594417766 to your computer and use it in GitHub Desktop.
Save josebraz/8cc302511d8b240400f6e6f594417766 to your computer and use it in GitHub Desktop.
Debounce
open class Debouncer<T>(
protected val scope: CoroutineScope,
protected val period: Long
) {
protected var scheduleJob: Job? = null
protected var lastRan: Long = -period
fun debounce(
arg: T,
block: suspend CoroutineScope.(T) -> Unit
): Boolean = debounce(arg, period, block)
protected fun debounce(
arg: T,
delay: Long,
block: suspend CoroutineScope.(T) -> Unit
): Boolean {
synchronized(this@Debouncer) {
scheduleJob?.cancel()
scheduleJob = scope.launch {
delay(delay)
synchronized(this@Debouncer) {
scheduleJob = null
lastRan = System.currentTimeMillis()
}
block(arg)
}
}
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment