Hi i have two long operation.. and i’d like launch...
# android
a
Hi i have two long operation.. and i’d like launch in parallel…
customScope.launch{
action1()
action2()
i’d like launch in parallel and when 2 methods end your action i have to invoke a method
r
Hey there! You would probably want to use
async()
instead of
launch()
in this case, so that can you can call
await()
and wait for the result(s). Check out: https://kotlinlang.org/docs/composing-suspending-functions.html#concurrent-using-async
a
Ok ..
*val* one = async { doSomethingUsefulOne() }
*val* two = async { doSomethingUsefulTwo() }
i don’t understand how invoke a method when both async has finished your actions
r
Ah. If you call
await()
on both of them, whichever finished first will return immediately, whereas the one that is taking longer will block until it's done.
So let's say one takes 10 seconds and two takes 5, if you call
await()
on both then it will block for 10 seconds, but as two already finished in the meantime, your execution time will be 10 seconds in total (roughly of course)
p
Copy code
customScope.launch {
  coroutineScope {
    launch { action1() }
    launch { action2() }
  }
  println("action1 and action2 finished")
  doSthNow()
}
1
This will launch a new coroutine which then launches action1 and 2 in parallel. Once the coroutineScope block exists, both actions completed
a
but are action1() and action1() launched in parallel?
p
Yes