kotlin - 如果 channel.send() 没有接收到任何值,channel 会保持我的协程运行吗?
问题描述
我开始使用android Channel
,kotlinx.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")
}
似乎如果没有从 发送的值inputChannel
,inputChannel.receive()
将永远不会返回值并且println(value)
不会运行,只会打印“start #1 coroutine”。
我的问题是当我什么也没收到#1
时我的协程发生了inputChannel
什么?它会陷入while(true)
循环并继续等待吗?如果是这样,它会永远运行吗?
解决方案
不,它不会在“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()
}
}
推荐阅读
- javascript - 如果 prop 未在 react 中定义,如何重定向到另一个页面
- asp.net-core - SignalR(asp.net 核心)不发送复杂类对象
- python - python - 如何在python的for循环中将不同的字典添加到同一个列表中?
- javascript - Vue.js:变量可以显示在, but cannot be used in mounted hook
I am new to Vue.js, I tried to load a file
config.json
from/public
folder so that some settings can be changed during runtime.I can now load
- python - 满足特定条件时执行函数
- c++ - C++中赋值运算符的返回类型
- javascript - 用jquery初始化画布
- javascript - 我的 React 应用程序没有在浏览器中自动重新加载
- android - React-native 发布版本导致模拟器出现“系统 UI 没有响应”错误
- c++ - unique_ptr 如何使用自定义删除器功能?