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

AdalPari

12/10/2020, 6:59 PM
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
t

tseisel

12/10/2020, 7:31 PM
This is probably the best resource I could give you to understand the difference, and when to use which : https://kotlinlang.org/docs/composing-suspending-functions.html#sequential-by-default
a

AdalPari

12/10/2020, 7:44 PM
Thank you. I meant that before, between and after foo calls there are code not related with
suspend
functions
@tseisel the link you sent me redirect to 404 error
So, if I understood correctly, in the second example, "// more sequential code 1" won't run until
foo1()
(suspend) is finished, while in the first example it will run because
foo1()
call runs independent
t

tseisel

12/10/2020, 7:50 PM
@AdalPari Wow, looks like the new Kotlin docs are not properly linked yet. Here is a working link : https://kotlinlang.org/docs/reference/coroutines/composing-suspending-functions.html
a

AdalPari

12/10/2020, 7:51 PM
Thanks!
3 Views