Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Used to do a trailing throttle of actions.
*/
internal class Throttler<A, B>(
private val delay: Long = 500,
private val action: (A) -> B
) {
private val target = AtomicReference<A>()
var future: Future<B>? = null
fun throttle(input: A): Future<B> {
target.set(input)
return future?.takeUnless { it.isDone } ?: schedule()
}
private fun schedule() = Futures.schedule {
sleep(delay)
action(target.get())
}.also { future = it }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment