https://kotlinlang.org logo
#coroutines
Title
# coroutines
z

Zoltan Demant

08/18/2022, 7:54 AM
Whats the recommended approach for using
scope.launch {}
from MainScope? Generally, the task itself will run with the "correct" dispatcher, for example: loading something from a database is always executed using
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
. But to me it seems that I might as well specify something like
Dispatchers.Default
in the launch block, so that all tasks are at least off-loaded from the main thread by default? As a real life scenario, I was just working on an issue where UI froze after the user had selected a file to import from; I had failed to realize that contentResolver.openInputStream(uri) was blocking rather than reading from the inputStream itself. If I had been using
Dispatchers.Default
, this wouldnt have been a problem. Now, instead I have to wrap each individual call like this (there arent many, but still) in a
withContext(Dispatchers.Default/IO)
.
android badvice 1
r

Robert Williams

08/18/2022, 9:45 AM
I'd say it's a hacky workaround that hides bugs rather than fixes them
If you have a suspend fun that blocks the calling thread that's always a bug in the suspend fun and not the caller's responsibility
t

tseisel

08/18/2022, 9:46 AM
Not all coroutines launched within the
MainScope
are expected to execute blocking operations. Sometimes you just need to execute suspend UI operations, for example waiting for a delay before retrying an operation.
suspend
functions should be main-safe, i.e. they should be designed to use another dispatcher internally, so that callers may run on any dispatcher without worying about blocking the main thread.
r

Robert Williams

08/18/2022, 9:47 AM
All of coroutines has been designed that the caller shouldn't know about threading details of things it calls
Blocking coroutines make your code less reusable (because everywhere needs to know to launch on a background thread)
And makes cancellation harder (because normally withContext acts as a yield point)
Plus assuming you have a single threaded UI-toolkit (otherwise you wouldn't care about blocking main thread) you'll need another context switch at the end to get back to main anyway
z

Zoltan Demant

08/18/2022, 10:06 AM
Thank you both, this is exactly what I needed to hear to understand that its actually a bad idea 🤌🏽
6 Views