gpt4 book ai didi

kotlin - GlobalScope 与 LifecycleOwner :CoroutineScope

转载 作者:行者123 更新时间:2023-12-02 12:53:46 26 4
gpt4 key购买 nike

假设 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)
}
}

state()返回的ReceiveChannel什么时候取消?这是内存泄漏吗?

最佳答案

documentation状态:

The running coroutine is cancelled when its receive channel is cancelled.

此外,它指出

Note: This is an experimental api. Behaviour of producers that work as children in a parent scope with respect to cancellation and error handling may change in the future.

结论:取消父作用域时的行为是不确定的,将来可能会发生变化。

这就是为什么对生产者使用 GlobalScope 并使用返回的 ReceiveChannel 来显式控制生命周期的最佳选择。 channel 不会自动关闭/取消。

关于kotlin - GlobalScope 与 LifecycleOwner :CoroutineScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com