Skip to content

Instantly share code, notes, and snippets.

@josebraz
Last active July 12, 2022 03:23
Show Gist options
  • Save josebraz/5c42eb3087875d476d614d9961426483 to your computer and use it in GitHub Desktop.
Save josebraz/5c42eb3087875d476d614d9961426483 to your computer and use it in GitHub Desktop.
Throttler
class Throttler<T>(
scope: CoroutineScope,
period: Long
): Debouncer<T>(scope, period) {
fun throttle(
arg: T,
block: suspend CoroutineScope.(T) -> Unit
): Boolean {
synchronized(this@Throttler) {
if (lastRan + period <= System.currentTimeMillis()) {
lastRan = System.currentTimeMillis()
scheduleJob?.cancel()
scheduleJob = null
scope.launch { block(arg) }
return true
}
}
val delay = period - (lastRan % period)
debounce(arg, delay, block)
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment