Why do I need await in a corutine if also withut u...
# coroutines
p
Why do I need await in a corutine if also withut using it, the line after a suspend function will be executed when the suspend function as ended? await seems to be redundant and unnecessary
lifecycleScope.launch() {
val response = retrofit.getSuperheroes("a")
Log.d("", response)
}
With await, seems to be exactly the same, the Log line will wait until response is received, like without await
lifecycleScope.launch() {
val deferred = async { retrofit.getSuperheroes("a") }
val response = deferred.await()
Log.d("", response)
}
So... why the existence of await?
y
async
is not
suspend
actually! It launches a new coroutine, and that coroutine is not guaranteed to (and likely won't) finish by the time
async
stops executing. The point of async is that you can use it to launch multiple coroutines in parallel, and then get a value out of them (see also
awaitAll
). In your example, indeed the await is entirely useless, so you just shouldn't be using it. It can however be useful if you had e.g.
getSuperheroes
and
getVillians
and you want to run both in parallel, so that you can start getting them both at the same time (this can help if e.g. one of them comes from a file while another from the network)
p
thanks
j
The short answer is that you need
await
because you used
async
, so the question you should be asking is rather Why do I need async?. And the answer is what Youssef replied. Now to elaborate a tiny bit more, using
async
+
await
is useful when you have some code between the
async
and the
await
, because this code will run concurrently with whatever is in the
async { ... }
block. In your case, you have no code between
async
and
await
, so nothing runs concurrently with
getSuperheroes
, which indeed makes the whole structure redundant.