-
Notifications
You must be signed in to change notification settings - Fork 24
About Async and Await
Basically Async
is used to compute the code asynchronously and Await
is used to return the result of that computation. They are called in suspending function.
In Kotlin, coroutines are used to write asynchronous code in a more sequential and readable manner. async
and await
are keywords often associated with coroutines, but it's important to note that they are not used in the same way as in some other languages like JavaScript.
In Kotlin coroutines, async
is used to start a coroutine that computes a result asynchronously, and await
is used to retrieve the result of that computation. However, they are typically used in conjunction with launch
and suspend
functions.
Here's a brief explanation of when to use async
and await
in Android Kotlin coroutines:
-
Use
async
when you want to perform concurrent tasks:- When you have multiple independent tasks that can be executed concurrently, you can use
async
to launch coroutines for each task. -
async
returns an instance ofDeferred
, which is a lightweight non-blocking future representing a value that may or may not be available.
val result1: Deferred<ResultType1> = async { // ... } val result2: Deferred<ResultType2> = async { // ... }
- When you have multiple independent tasks that can be executed concurrently, you can use
-
Use
await
to retrieve the results:- After launching multiple
async
coroutines, you can useawait
to retrieve the results of each coroutine when needed. -
await
is a suspending function, meaning it can only be called from within a coroutine or another suspending function.
val result1: ResultType1 = result1.await() val result2: ResultType2 = result2.await()
- After launching multiple
-
Use
async
andawait
within asuspend
function:- It's common to use
async
andawait
within asuspend
function to perform asynchronous operations. - The
async
coroutines can be launched and awaited within asuspend
function, allowing you to structure your asynchronous code more sequentially.
suspend fun performAsyncTasks(): CombinedResult { val result1: Deferred<ResultType1> = async { /* ... */ } val result2: Deferred<ResultType2> = async { /* ... */ } val combinedResult = CombinedResult(result1.await(), result2.await()) return combinedResult }
- It's common to use
Remember that coroutines are generally used to handle asynchronous operations in a more structured and readable way, making the code easier to reason about. Always be mindful of the coroutine context, and try to avoid blocking operations within coroutines whenever possible.