Glen
08/03/2021, 8:39 PMGlen
08/03/2021, 8:42 PMCasey Brooks
08/03/2021, 8:45 PMfun decode(): Bitmap? {
return runBlocking {
val value = decodeInternal() // a suspending function
value // return the value
}
}
fun decode(onCompleted: (Bitmap?)->Unit) {
GlobalScope.launch {
val value = decodeInternal() // a suspending function
onCompleted(value) // send the value through a callback
}
}
Casey Brooks
08/03/2021, 8:47 PMDispatchers.Main
, it will already be set to the appropriate value for the platformCasey Brooks
08/03/2021, 8:49 PMGlen
08/03/2021, 9:16 PMGlen
08/03/2021, 9:43 PMGlen
08/03/2021, 9:44 PMCasey Brooks
08/03/2021, 10:11 PMGlobalScope
now needs a special annotation to use, because it’s generally that should be avoided. So not requiring any special coroutines API really isn’t a feature as much as it is a bug. But all the major Android components now natively work with coroutines in the -ktx
libraries, so it’s not difficult at all to get ahold of an appropriate coroutine scope (lifecycleScope
in Activities/Fragments, WorkManager CoroutineWorker
, etc).
And again, if you’re pulling in the dependency on coroutines, you should be following the principles of Structured Concurrency properly. Android development nowadays expects that you’re using coroutines already, and it also expects that anything else using coroutines is following those Structured Concurrency principles, so that everything works nicely with each other. But in the current setup, there’s no real benefit over a normal Thread/Executor, it’s just pulling in a large library but ignoring its benefitsNick Allen
08/03/2021, 11:29 PMlaunch
does not suspend. It starts a coroutine and does not wait for it to finish.
var x = 0
someScope.launch {
someBlockingCode();
x = 20
}
println(x) // x is probably still 0.
Glen
08/04/2021, 8:00 PM