Junior — Middle
Can you explain the differences between launch and async functions when using Coroutine Builder in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, when working with coroutines, launch and async are Coroutine Builders, but they serve different purposes:
-
launchstarts a coroutine that runs asynchronously and does not return a result. It is used for executing tasks where the result is not needed, such as side effects. -
asyncstarts a coroutine that returns aDeferred<T>— a deferred result that can be obtained usingawait(). It is used when you need to get the result of an asynchronous operation.
Example:
val job = scope.launch {
// runs asynchronously, no result returned
}
val deferred = scope.async {
// runs asynchronously, returns a result
return@async 42
}
runBlocking {
val result = deferred.await() // get the result
println(result) // 42
}
In summary, launch is for starting tasks without a result, async is for starting tasks with a result.