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

ubu

12/01/2020, 1:45 PM
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

Jon Michael Aanes

12/01/2020, 1:53 PM
No, they are not sequential by default. They can be scheduled in any order.
✔️ 1
r

rtsketo

12/01/2020, 1:58 PM
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

christophsturm

12/01/2020, 2:03 PM
if you want to run it sequentially just do it without a launch block
s

Shalom Halbert

12/01/2020, 4:25 PM
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

Chris Ruddell

12/01/2020, 5:03 PM
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

ubu

12/02/2020, 9:51 AM
@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

christophsturm

12/02/2020, 9:52 AM
yes
3 Views