Your function won’t send the last element until t...
# coroutines
d
Your function won’t send the last element until the next one arrive (if ever). I think something like the following can be used (not tested):
Copy code
fun <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)
    }
}
👍 1