Last active
July 12, 2022 03:23
-
-
Save josebraz/5c42eb3087875d476d614d9961426483 to your computer and use it in GitHub Desktop.
Throttler
This file contains 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
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