spierce7
05/29/2020, 4:09 PMGlobalScope
. When would it be bad to use GlovalScope
, and when would it be good?Casey Brooks
05/29/2020, 4:14 PMGlobalScope
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 gonespierce7
05/29/2020, 4:39 PMNonCancellable
, is there really any difference?Zach Klippenstein (he/him) [MOD]
05/29/2020, 5:12 PMGlobalScope
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.zak.taccardi
05/29/2020, 9:00 PMIf 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 thinguli
06/03/2020, 3:53 PMGlobalScope
?Zach Klippenstein (he/him) [MOD]
06/03/2020, 4:17 PMGlobalScope
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.zak.taccardi
06/03/2020, 4:18 PMwhy is that better than using the already existing GlobalScopeFor the same benefits that using DI gives you
uli
06/03/2020, 4:21 PMGlobalScope
. You can also inject GlobalScope
zak.taccardi
06/03/2020, 4:24 PMCoroutineScope(EmptyCoroutineContext)
if you want to duplicate that behavioruli
06/03/2020, 4:55 PMzak.taccardi
06/07/2020, 6:42 PMGlobalScope
as the backing implementation,
someone may accidentally refer to GlobalScope
, thinking that would be okay