Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pablisco
Created May 17, 2018 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablisco/41da7c68ec14636a26fc67c6b724a71c to your computer and use it in GitHub Desktop.
Save pablisco/41da7c68ec14636a26fc67c6b724a71c to your computer and use it in GitHub Desktop.
/**
* 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