kotlin - GlobalScope vs LifecycleOwner:CoroutineScope
问题描述
假设 CoroutineScope 是由一些生命周期感知组件实现的,例如Presenter
. 什么时候最好使用 GlobalScope.produce 和 CoroutineScope.produce;
interface IPresenter, CoroutineScope {
fun state(): ReceiveChannel<Event>
}
class Presenter(
override val coroutineContext: CoroutineContext
): IPresenter, DefaultLifecycleObserver {
fun state(): ReceiveChannel<Event> = GlobalScope.produce {
send( SomeEvent() )
}
fun someOperation() = produce {
send( SomeEvent() )
}
override fun onDestroy(owner: LifecycleOwner) {
coroutineContext.cancel()
owner.lifecycle.removeObserver(this)
}
}
ReceiveChannel 什么时候返回的state()
cancelled?这是内存泄漏吗?
解决方案
该文档指出:
正在运行的协程在其接收通道被取消时被取消。
此外,它指出
注意:这是一个实验性的 api。在父范围内作为子级工作的生产者在取消和错误处理方面的行为将来可能会发生变化。
结论:取消父范围时的行为是未指定的,并且将来可能会发生变化。
这就是为什么它是GlobalScope
用于生产者并使用返回ReceiveChannel
来显式控制生命周期的最佳选择。该频道不会自动关闭/取消。
推荐阅读
- javascript - 如何修复 jQuery 中的 ReferenceError
- macos - .zshrc 上的 PS1 输出字符串而不是所需的输出
- javascript - 如何让我的机器人可以容纳 2 个参数命令 DiscordJS
- r - 通过括号 [] 将字符串应用到子集
- javascript - 如何在 Visual Studio Code 上的 Vue 文件中启用 JavaScript 类型检查?
- javascript - 如何将自定义道具传递给反应登录按钮
- python - 将索引和值作为字典返回
- r - 有没有办法将 chemarr 的乳胶表达式用于 bookdown 包的 `gitbook` 格式?
- python - 方法内的递归
- python - 如何仅计算连续天数的百分比变化?