GlobalScope 与 LifecycleOwner:CoroutineScope

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

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 来显式控制生命周期的最佳选择。频道不会自动获取 closed/cancelled.