Skip to content

Instantly share code, notes, and snippets.

@lixiaoyi
Last active February 27, 2019 16:09
Show Gist options
  • Save lixiaoyi/6f40a244fee2edb0a078ba2410f6d77e to your computer and use it in GitHub Desktop.
Save lixiaoyi/6f40a244fee2edb0a078ba2410f6d77e to your computer and use it in GitHub Desktop.
ReceiveChannel throttle function
fun <T> ReceiveChannel<T>.throttle(
settleTime: Long = 300,
scope: CoroutineScope
): ReceiveChannel<T> = scope.produce {
var job: Job? = null
consumeEach {
job?.cancel()
job = launch {
delay(settleTime)
send(it)
}
}
job?.join() //waiting for the last job to end
}
fun main(args: Array<String>) = runBlocking {
val channel = produce {
(0..100).forEach {
println("send$it")
send(it)
delay(Random().nextInt(400).toLong())
}
}
channel.throttle(300, GlobalScope).consumeEach { println("Yay!") }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment