Middle
What is the difference between launch and async/await in Kotlin?
sobes.tech AI
Answer from AI
launch starts a coroutine that performs work and does not return a result. It is intended for executing tasks that do not require blocking to wait for completion.
async starts a coroutine that performs work and returns a result of type Deferred<T>. To get the result, await() is used, which suspends the current coroutine until the asynchronous task completes. async/await are used when you need to obtain a result from an asynchronous operation.
Example usage:
// launch - without a return value
fun doSomethingAsync() = GlobalScope.launch {
delay(1000)
println("Work completed")
}
// async/await - with a return value
suspend fun calculateSomethingAsync(): Int = GlobalScope.async {
delay(1000)
42
}.await()
suspend fun main() {
doSomethingAsync()
val result = calculateSomethingAsync()
println("Result: $result")
}
Summary table of differences:
| Feature | launch | async/await |
|---|---|---|
| Return type | Job | Deferred<T> |
| Waiting | Does not block (fire and forget) | Requires await() for blocking wait for result |
| Usage | For launching tasks that do not require returning a result | For launching tasks whose result is needed for further logic |
| Error handling | Through CoroutineExceptionHandler | Through try-catch block when calling await() |