Last active
February 27, 2019 16:09
-
-
Save lixiaoyi/6f40a244fee2edb0a078ba2410f6d77e to your computer and use it in GitHub Desktop.
ReceiveChannel throttle function
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
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