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

vineethraj49

11/05/2019, 12:57 AM
do
test1()
and
test2()
end up doing the same? (my guess: yes) test1:
async(<http://Dispatchers.IO|Dispatchers.IO>) { [...] }
test2:
suspend fun logic() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { [...] }; async { logic() }
if so, which is more idiomatic?
s

streetsofboston

11/05/2019, 1:07 AM
Both are good. The 2nd a bit better because you decided the refactor out the common code. In my opinion, it is best to set/change the Dispatcher to close as possible to the code that really needs it. In your case, the code-block that blocks a thread (openStream and readBytes) is the one you’d want to wrap in a Dispatcher.IO, since that dispatcher is fit for that purpose
v

vineethraj49

11/05/2019, 1:10 AM
my take is:
Dispatchers.Default
for everything,
<http://Dispatchers.IO|Dispatchers.IO>
for my network calls; assuming that, is spawning CPU intensive workload on
Dispatchers.Default
or
async(Dispatchers.Default)
1. both bad? 2. both bad, but second slightly worse 3. first is ok, second is not
s

streetsofboston

11/05/2019, 1:24 AM
Default
is for CPU intensive jobs, the thread pool is pegged to number of CPU cores.
IO
is for code that blocks (network, io in general, code that has Thread.sleep, etc) Note that they do share threads between their pools, so you won’t get deadlocks (easily).
6 Views