Cancel event listener when channel is closed

This commit is contained in:
Him188 2020-03-06 10:19:37 +08:00
parent baa3c2109e
commit b17c30853c

View File

@ -11,6 +11,7 @@
package net.mamoe.mirai.event
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
@ -172,9 +173,12 @@ inline fun <reified E : Event> CoroutineScope.incoming(
capacity: Int = Channel.UNLIMITED
): ReceiveChannel<E> {
return Channel<E>(capacity).apply {
subscribeAlways<E>(coroutineContext) {
val listener = subscribeAlways<E>(coroutineContext) {
send(this)
}
this.invokeOnClose {
listener.cancel(CancellationException("ReceiveChannel closed", it))
}
}
}