Just a quick question about what is better and dif...
# coroutines
t
Just a quick question about what is better and differences between GlobalScope and withContext(NonCancellable) on Android Is there any advantage / problem with one of those functions? Typical use case would be using proper scoped context in an Activity, but wanting that a coroutine that write something to the DB is not cancelled at the end of the activity. Or maybe there's another alternative?
e
IMHO,
GlobalScope
better describes intent here (of a separate non-scoped background process)
Functionally, the differences between
GlobalScope.launch { ... }
and
launch { ... withContext(NonCancellable) { ... } .. }
is that the latter also inherits dispatcher, which if likely not something you want in this case.
I’d actually define a separate
dbScope
and consistently use it for such tasks to be clear. It could be something like
val dbScope = GlobalScope + <http://Dispatchers.IO|Dispatchers.IO>
t
The final plan is to use a workerpool for that to also limit concurrency but I'm still having issues with that https://github.com/Kotlin/kotlinx.coroutines/issues/830#issuecomment-441619668. But thanks for confirming that GlobalScope can be used for such needs, docs have plenty of don't use it 🙂