Explain the differences between launch, async, and runBlocking functions in Kotlin coroutines.
sobes.tech AI
Answer from AI
In Kotlin, coroutines allow writing asynchronous code more simply. Here are the differences between launch, async, and runBlocking:
-
launch— starts a new coroutine that runs in parallel but does not return a result. Used for background tasks where the result is not needed. -
async— starts a coroutine that returns aDeferred<T>, which is a promise of a result. Allows obtaining the result viaawait(). Used when you need to get the result of an asynchronous operation. -
runBlocking— blocks the current thread until the coroutine completes. Usually used in the main function or tests to run coroutines from synchronous code.
Example:
fun main() = runBlocking {
launch {
println("Coroutine without result launched")
}
val deferred = async {
delay(1000)
return@async "Result"
}
println("Waiting for result: ${deferred.await()}")
}
Here, runBlocking launches coroutines and waits for their completion, launch starts a task without a result, async — with a result.