Pablo
11/21/2024, 11:00 PMlifecycleScope.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?Youssef Shoaib [MOD]
11/21/2024, 11:07 PMasync
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)Pablo
11/21/2024, 11:09 PMJoffrey
11/21/2024, 11:37 PMawait
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.