Guest User

Untitled

a guest
May 22nd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.49 KB | None | 0 0
  1. /**
  2. * Used to do a trailing throttle of actions.
  3. */
  4. internal class Throttler<A, B>(
  5. private val delay: Long = 500,
  6. private val action: (A) -> B
  7. ) {
  8.  
  9. private val target = AtomicReference<A>()
  10.  
  11. var future: Future<B>? = null
  12.  
  13. fun throttle(input: A): Future<B> {
  14. target.set(input)
  15. return future?.takeUnless { it.isDone } ?: schedule()
  16. }
  17.  
  18. private fun schedule() = Futures.schedule {
  19. sleep(delay)
  20. action(target.get())
  21. }.also { future = it }
  22.  
  23. }
Add Comment
Please, Sign In to add comment