我开始在安卓的kotlinx.coroutines.channels中使用Channel,在使用频道的时候,我对我的coroutineScope的生命周期感到困惑。
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)也不会运行,只会打印"start #1协程“。
我的问题是,当inputChannel没有收到任何东西时,我的#1协程发生了什么?它是否会遇到while(true)循环并一直等待?如果是这样,它会永远运行吗?
发布于 2020-11-04 16:56:13
不,它不会在"while(true)“循环中运行。
相反,Coroutine#1将在"inputChannel.receive()“行被挂起。
有关更多细节,请访问https://kotlinlang.org/docs/reference/coroutines/channels.html#buffered-channels
关于CoroutineScope的“生命周期”,应该根据场景进行显式管理。
例如,在下面的"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()
}
}https://stackoverflow.com/questions/64568523
复制相似问题