defhlt
07/12/2017, 11:11 PMfun <T> ReceiveChannel<T>.debounce() = produce<T>(CommonPool) {
val timeout = { launch(context) { delay(300) } }
val source = this@debounce
val NONE = Object()
var last: Any? = NONE
while (!source.isClosedForReceive) {
select<Unit> {
if (last != NONE) { // no need to timeout since we have nothing to send
timeout().onJoin {
send(last as T)
last = NONE
}
}
source.onReceiveOrNull {
if (it != null) {
last = it
}
}
}
}
if (last != NONE) {
send(last as T)
}
}