首页 > 解决方案 > 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?这是内存泄漏吗?

标签: kotlinconcurrencyandroid-lifecyclekotlinx.coroutines

解决方案


文档指出:

正在运行的协程在其接收通道被取消时被取消。

此外,它指出

注意:这是一个实验性的 api。在父范围内作为子级工作的生产者在取消和错误处理方面的行为将来可能会发生变化。

结论:取消父范围时的行为是未指定的,并且将来可能会发生变化。

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


推荐阅读