假设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()返回何时取消?这是内存泄漏吗?
发布于 2018-11-27 09:51:07
文档指出:
当其接收信道被取消时,运行协同线被取消。
此外,它还指出
注意:这是一个实验性的api。在父范围内作为子级工作的生产者在取消和错误处理方面的行为可能会在未来发生变化。
结论:家长范围取消时的行为未具体说明,并有可能在今后发生变化。
这就是为什么对生产者使用GlobalScope并使用返回的ReceiveChannel显式控制生命周期是最好的选择。频道不会自动关闭/取消。
https://stackoverflow.com/questions/53490674
复制相似问题