首页 > 解决方案 > 如果 channel.send() 没有接收到任何值,channel 会保持我的协程运行吗?

问题描述

我开始使用android Channelkotlinx.coroutines.channels我对使用通道时 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")
}

似乎如果没有从 发送的值inputChannelinputChannel.receive()将永远不会返回值并且println(value)不会运行,只会打印“start #1 coroutine”。

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

标签: kotlinkotlin-coroutines

解决方案


不,它不会在“while(true)”循环中运行。

而是 Coroutine#1 将在“inputChannel.receive()”行暂停

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

关于 CoroutineScope 的“Lifetime”,应该根据 Scenario 显式管理。

例如,在“MyNotificationListener Service”下面,CoroutineScope 与 SERVICE 的 LIFECYCLE 相关联,即 Coroutine 在“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()
        }
    }

推荐阅读