deviant
07/12/2017, 6:24 PMthrottle
feature with coroutines
suspend fun <T> ReceiveChannel<T>.consumeThrottled(throttling: Long, action: (T) -> Unit) {
var timestamp = 0L
for (data in this) {
if (timestamp + throttling < System.currentTimeMillis()) {
timestamp = System.currentTimeMillis()
action(data)
}
}
}
is there a proper way?deviant
07/13/2017, 7:21 AMYour function won’t send the last elementit will be sent if throttled time is passed, which is fine for my case. btw i like solution with
select
clause 👍deviant
07/13/2017, 11:17 AMfun <T> ReceiveChannel<T>.throttle(throttling: Long) = produce(Unconfined) {
val original = this@throttle
var t: Job? = null
for (item in original) {
if (t == null || t.isCompleted) {
send(item)
t = launch(context) { delay(throttling) }
}
}
}