Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GlobalScope vs LifecycleOwner:CoroutineScope

assuming that CoroutineScope is implemented by some lifecycle-aware component like Presenter. when is it preferable to use GlobalScope.produce vs 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)
  } 
}

when is the ReceiveChannel returned by state() cancelled? is this a memory leak?

like image 209
xst Avatar asked Jan 27 '26 09:01

xst


1 Answers

The documentation states:

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

Additionally, it states

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.

Conclusion: the behavior when the parent scope is cancelled is unspecified and liable to change in the future.

This is why it's the best option to use GlobalScope for the producer and use the returned ReceiveChannel to explicitly control the lifecycle. The channel won't get automatically closed/cancelled.

like image 75
Marko Topolnik Avatar answered Jan 29 '26 00:01

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!