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

v79

12/01/2018, 8:12 AM
Suppose I have an arbitrary list of
suspend
functions p(), q(),..., and I want them to run in parallel/concurrently. Is this a valid approach?
g

gildor

12/01/2018, 11:24 AM
yes, you can use launch (if you don’t need result of invocation) This covered in official guide https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/composing-suspending-functions.md#concurrent-using-async
v

v79

12/01/2018, 12:44 PM
Thanks. This is all very new to me 🙂
u

uli

12/01/2018, 1:30 PM
Why do you need the outer launch?
v

v79

12/01/2018, 1:36 PM
Turns out I don't, it just appeared in the tutorial I was working from and I copied blindly 🙂. I've taken it out.
d

Dico

12/02/2018, 1:52 AM
I don't think the code you wrote works. The
launch
invocations are using dispatcher provided by
runBlocking
scope, which uses the
Which queues the coroutines on the same thread
Instead, you can consider using GlobalScope, or even better, declaring your function as an extension on CoroutineScope interface. You can also put it in a component that has its own CoroutineScope.
Or just pass a dispatcher as context to the top most launch
u

uli

12/02/2018, 4:16 AM
@Dico why do you think the code would not work on a single thread?
If all coroutines are surrended must of the time a single thread will do just fine.
d

Dico

12/02/2018, 7:41 AM
What I meant to say is that I think the code will run on a single thread (as I eloquently explained) while the poster explicitly wants to run tasks in parallel.
@uli
2 Views