Kotlin 如果频道没有';无法通过channel.send()接收任何值?
我开始在android的Kotlin 如果频道没有';无法通过channel.send()接收任何值?,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我开始在android的kotlinx.coroutines.channels中使用Channel,我对使用Channel时我的coroutineScope的生命周期感到困惑 val inputChannel=Channel() 启动(Dispatchers.Default){ // #1 println(“开始#1协同程序”) val值=inputChannel.receive() println(值) } 启动(Dispatchers.Default){ inputChannel.send(
kotlinx.coroutines.channels
中使用Channel
,我对使用Channel时我的coroutineScope的生命周期感到困惑
val inputChannel=Channel()
启动(Dispatchers.Default){
// #1
println(“开始#1协同程序”)
val值=inputChannel.receive()
println(值)
}
启动(Dispatchers.Default){
inputChannel.send(“foo”)
}
似乎如果没有从inputChannel
发送值,inputChannel.receive()
将永远不会返回值,println(value)
将不会运行,只会打印“开始#1协同程序”
我的问题是,当inputChannel
没有接收任何内容时,我的#1
协同程序发生了什么?它是否在while(true)循环中运行并保持等待?如果是,它会永远运行吗?不,它不会在“while(true)”循环中运行
相反,协程#1将在“inputChannel.receive()行”处挂起
详情请浏览
关于CoroutineScope的“生存期”,应该根据场景显式地管理它
例如,在下面的“MyNotificationListener服务”中,协同路由作用域与服务的生命周期相关联,即协同路由在“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()
}
}