GlobalScope与LifecycleOwner:CoroutineScope

时间:2018-11-26 23:35:26

标签: kotlin concurrency android-lifecycle kotlinx.coroutines

假设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被取消?这是内存泄漏吗?

1 个答案:

答案 0 :(得分:1)

documentation指出:

  

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

另外,它指出

  

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

结论:取消父范围的行为是不确定的,将来可能会更改。

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