首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果通道没有接收到channel.send()的任何值,通道会让协程保持运行吗?

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

Stack Overflow用户
提问于 2020-10-28 15:50:26
回答 1查看 173关注 0票数 0

我开始在安卓的kotlinx.coroutines.channels中使用Channel,在使用频道的时候,我对我的coroutineScope的生命周期感到困惑。

代码语言:javascript
复制
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)循环并一直等待?如果是这样,它会永远运行吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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()“中取消协程。

代码语言:javascript
复制
     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()
        }
    }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64568523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档