My team mates and I are noticing that a lot of peo...
# coroutines
s
My team mates and I are noticing that a lot of people / blogs discouraging the general use of
GlobalScope
. When would it be bad to use
GlovalScope
, and when would it be good?
c
GlobalScope
is discouraged because it might allow tasks to run for longer than they need do, holding onto system resources beyond their intended “scope”. If your app only has a single “lifetime” (like a simple CLI app), then
GlobalScope
should be fine. If it has a more complex lifecycle (such as Android), you’ll want to use a more appropriate scope that properly cancels work when moving between screens. Most background work is tied to a parcicular screen (do some work, then update the UI), so you want to make sure to cancel the work when the UI that would be updated is gone
s
So if I’m using coroutines with
NonCancellable
, is there really any difference?
z
Yes. Using
GlobalScope
doesn't make your coroutine non-cancellable, it just opts it out of structured concurrency. That's why it's discouraged, because structured concurrency is what prevents leaks and makes coroutines less boilerplatey. You can still cancel coroutines launched in the global scope if you have a reference to their job.
NonCancellable
actually prevents your coroutine from being cancelled.
👍 2
z
If your app only has a single “lifetime” (like a simple CLI app), then GlobalScope should be fine.
I actually don’t think there is a scenario where
GlobalScope
usage is fine. You can literally just do
CoroutineScope(dispatchers.default)
- store it somewhere. and it’s effectively the same thing
☝️ 2
u
So @zak.taccardi why is that better than using the already existing
GlobalScope
?
z
I think more important than creating a custom scope vs using
GlobalScope
is that you don’t hard code a dependency on
GlobalScope
. Where possible, inherit a scope, and where there’s no implicit scope, inject the base scope to use. And then whether the scope being provided happens to be
GlobalScope
or some custom scope right now, it’s easy to change to a more managed scope in the future as your app scales.
👍 3
z
why is that better than using the already existing GlobalScope
For the same benefits that using DI gives you
u
Thanks @Zach Klippenstein (he/him) [MOD]. @zak.taccardi, agreed. Like @Zach Klippenstein (he/him) [MOD] wrote, DI is the point. not discarding
GlobalScope
. You can also inject
GlobalScope
z
you still should not use global scope though. Just create
CoroutineScope(EmptyCoroutineContext)
if you want to duplicate that behavior
u
And why is that better than using the already existing GlobalScope 😉
z
If you use
GlobalScope
as the backing implementation, someone may accidentally refer to
GlobalScope
, thinking that would be okay