Junior — Middle
What is the difference between launch and async functions when using coroutines in Kotlin?
sobes.tech AI
Answer from AI
The launch and async functions in Kotlin are used to start coroutines but serve different purposes and return different types.
-
launchstarts a coroutine that runs in the background and does not return a result. It returns aJobobject, which can be used to control the coroutine (e.g., cancel it). -
asyncstarts a coroutine that returns a result in the future. It returns aDeferred<T>object, which is a subclass ofJoband allows obtaining the result viaawait().
Example:
val job = scope.launch {
// perform a task without a result
}
val deferred = scope.async {
// compute and return a result
42
}
runBlocking {
val result = deferred.await() // get the result
println(result) // 42
}
Summary:
- Use
launchwhen no result is needed. - Use
asyncwhen you need to get the result of an asynchronous operation.