Fernando Branbila Cunha Junior
09/08/2020, 12:45 AMfun main() {
GlobalScope.launch {
val deferredUser = getUserByIdAsync(1)
val data = deferredUser.await()
print(data)
}
}
private suspend fun getUserByIdAsync(userId: Int) =
GlobalScope.async {
println("Retrieving user from network")
delay(3000)
println("Still on coroutine")
User(userId, "John", "Silva")
}
Adam Powell
09/08/2020, 1:04 AMmain
ends before the coroutine it launches completes, or perhaps even before it begins. Idiomatically one does not return Deferred
from functions and instead declares functions as suspend
that need to do suspending work. Your code would be better rewritten as:
suspend fun main() {
val user = getUserById(1)
print(data)
}
private suspend fun getUserById(userId: Int) {
println("Retrieving user from network")
delay(3000)
return User(userId, "John", "Silva")
}
Adam Powell
09/08/2020, 1:06 AMsuspend fun fetchTwo() = coroutineScope {
val one = async { getUserById(1) }
val two = async { getUserById(2) }
println("user one: ${one.await()} two: ${two.await()}")
}
Fernando Branbila Cunha Junior
09/08/2020, 1:18 AMAdam Powell
09/08/2020, 1:52 AMjulian
09/08/2020, 2:25 AMrunBlocking
.