Hi, I'm new to coroutines and I would appreciate some clarification.
I'm following different examples of basic coroutines and I'm seeing these two ways of structuring the code. What are the differences, pros and cons of them?
Suspend funs to call:
Copy code
suspend fun foo1() // function
suspend fun foo2() // function
First approach:
Copy code
// sequential code
viewModelScope.launch { foo1() }
// more sequential code
viewModelScope.launch { foo2() }
// more sequential code}
Second approach:
Copy code
viewModelScope.launch {
// sequential code
foo1()
// more sequential code
foo2()
// more sequential code
}
I've also saw this second approach with
async
calls inside the main
launch
one.
Thanks!
b
bezrukov
12/10/2020, 7:13 PM
First approach is not sequential, you launched two asynchronous coroutines, foo1 and foo2 will run concurrently