如果通道没有通过 channel.send() 接收任何值,它会让我的协程保持运行吗?



我开始在android的kotlinx.coroutines.channels中使用Channel,在使用通道时,我对我的协同作用域的寿命感到困惑。

val inputChannel = Channel<String>()
launch(Dispatchers.Default) {
// #1
println("start #1 coroutine")
val value = inputChannel.receive()
println(value)
}
launch(Dispatchers.Default) {
inputChannel.send("foo")
}

似乎如果没有从inputChannel发送的值,inputChannel.receive()将永远不会返回值,并且println(value)将不会运行,只有"0";启动#1协同程序";将被打印。

我的问题是,当inputChannel什么都没收到时,我的#1协同程序发生了什么?它是否会进入while(true)循环并继续等待?如果是,它会永远运行吗?

否,它不会在"而(true(";环

相反,Coroutine#1将被悬挂在";inputChannel.rereceive((";

更多详细信息,请访问https://kotlinlang.org/docs/reference/coroutines/channels.html#buffered-通道

关于";寿命";对于CoroutineScope,它应该基于Scenario进行显式管理。

例如,在下面的";MyNotificationListener服务";,CoroutineScope被绑定到服务的生命周期,即;onCreate(("并在";onDestroy((">

class MyNotificationListener : NotificationListenerService() {
private val listenerJob = SupervisorJob()
private val listenerScope = CoroutineScope(listenerJob + Dispatchers.Default)

override fun onCreate() {
// Launch Coroutines 
listenerScope.launch {
}
}
override fun onDestroy() {
// Cancel the Coroutines
listenerJob.cancel()
}
}

最新更新