Why not just rewrite it like: ``` val first: Defe...
# coroutines
g
Why not just rewrite it like:
Copy code
val first:  Deferred<Unit> = async { 
   firstTask().let { doFirstStuff() }
}
val second: Deferred<Unit> = async {    
    secondTask().let { doSecondStuff() }
}
first.await()
second.await()
b
Ah I see.
doFirstStuff
and
doSecondStuff
needs to be done on the UI thread in my case. In this example they will be called on another thread, right?
g
You can run them on any thread
just use
Copy code
withContext(UI) { doFirstStuff() }
also if you do this for UI don’t forget to manage UI lifecycle (probably you want to cancel those tasks in case of UI destroy)
But you right, async by default runs all the task on CommonPool dispatcher
b
Ah thanks 🙂 I think maybe in my case another
launch
will be useful. But I wasn't sure if nestled
launches
is good/idiomatic
g
nested launch? I don’t see why do you need nested launch
I mean:
Copy code
launch {
    val result = firstTask()
    withContext(UI) { result.doFirstStuff() }
}
launch {
    val result = secondTask()
    withContext(UI) { result.doSecondStuff() }
}
Or in opposite way, you can use UI context for launch and wrap secondTask (it’s not always necessary, depends on what firstTask/secondTask does)
b
In my case I'm already inside a launch. But I should probably go back and refactor when I start the first launch
g
Oh, I see, yes, of course choice between async/launch/withContext always based on your case and what is more convenient and correct for your semantics
nothing wrong with nested launch if it works for you. It’s just one coroutine just starts some child coroutines
b
Ok! I think this last example will work nicely in my case if I restructure the code a bit. Thanks a lot!