Hello there! A quick question here. When inside so...
# coroutines
u
Hello there! A quick question here. When inside some method inside a ViewModel I launch two coroutines:
Copy code
fun someFun() {
   val job1 = viewModelScope.launch { operation1() }
   val job2 = viewModelScope.launch { operation2() } 
}
Are these two operations sequential by default? Operation in the first launch block is completed, and only then, the second operation is started.
🚫 3
j
No, they are not sequential by default. They can be scheduled in any order.
✔️ 1
r
You can use job1.join() if for some reason you want to wait for it to complete before starting job2, but that kinda defeats its purpose.
c
if you want to run it sequentially just do it without a launch block
s
Could be incorrect, but my understanding is: All work that runs on the
Main
dispatcher from different `CoroutineScope`s (e.g. two `viewModelScope`s) are indirectly run sequentially because the work will run on the UI thread. It’s worth noting that the work does not start immediately, unlike if you were to run the work outside of a
CoroutineScope
. Please correct me if that’s wrong.
c
A launch block does not necessarily contain code that all resides within the same scope. So even if it was launched on Main, it might have calls to IO:
Copy code
scope.launch {
    someUiCall()
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) { someNetworkCall() }
    someUiCall()
}
So two launch blocks called on the Main scope won’t necessarily be run sequentially
👍 2
u
@christophsturm, do you mean something like:
Copy code
viewModelScope.launch {
   operation1()
   operation2()
}

suspend fun operation1() { … }
suspend fun operation2() { … }
in this case, will operations be executed sequentially?
c
yes