kotlin channel使用注意点

kotlinx.coroutines.channels.ClosedSendChannelException: Channel was closed
at kotlinx.coroutines.channels.Closed.getSendException(AbstractChannel.kt:1107)
at kotlinx.coroutines.channels.AbstractSendChannel.helpCloseAndResumeWithSendException(AbstractChannel.kt:230)
at kotlinx.coroutines.channels.AbstractSendChannel.access$helpCloseAndResumeWithSendException(AbstractChannel.kt:19)
at kotlinx.coroutines.channels.AbstractSendChannel.sendSuspend(AbstractChannel.kt:220)
at kotlinx.coroutines.channels.AbstractSendChannel.send(AbstractChannel.kt:136)
at kotlinx.coroutines.channels.ChannelCoroutine.send(Unknown Source:2)

因为 channel在另一个flow/channel里, 而kotlin的 job与channel 都是带 group概念的, 一个顶层job/channel关闭,会导致在其中的其他 也关闭

flow/channelFlow不能用时,可以使用 callbackFlow

https://blog.csdn.net/androiddevs/article/details/116078525

channelFlow 可以在不同的 CoroutineContext 或协程之外使用 offer(trySend) 方法发送数据。但一定要在block块内添加

awaitClose { channel.close(Throwable("完成")) }

 

posted on 2022-11-28 12:31  caosiqiao  阅读(200)  评论(0编辑  收藏  举报

导航