launch
vs async
fun CoroutineScope.launch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> Unit
): Job
Launches a new coroutine without blocking the current thread and returns a reference to the coroutine as a Job
. The coroutine is cancelled when the resulting job is cancelled. 1
fun <T> CoroutineScope.async(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T
): Deferred<T>
Creates a coroutine and returns its future result as an implementation of Deferred
. The running coroutine is cancelled when the resulting deferred is cancelled. The resulting coroutine has a key difference compared with similar primitives in other languages and frameworks: it cancels the parent job (or outer scope) on failure to enforce structured concurrency paradigm. To change that behaviour, supervising parent (SupervisorJob
or supervisorScope
) can be used. 2
The difference is that the launch{}
returns a Job
and does not carry any resulting value whereas the async{}
returns an instance of Deferred<T>
, which has an await()
function that returns the result of the coroutine. 3
suspend fun example() {
viewModelScope.launch {
//Perform some task (Not possible to return result)
}
val asyncDeferred = viewModelScope.async {
//Perform some task (Result can be returned)
return@async 3
}
val result = asyncDeferred.await() //equals 3
}
Typically, you should launch
a new coroutine from a regular function, as a regular function cannot call await
. Use async
only when inside another coroutine or when inside a suspend function and performing parallel decomposition. 4
Warning. launch
and async handle exceptions differently. Since async
expects an eventual call to await
, it holds exceptions and rethrows them as part of the await
call. This means if you use async
to start a new coroutine from a regular function, you might silently drop an exception. These dropped exceptions won’t appear in your crash metrics or be noted in logcat. 5
Links
Launch vs Async in Kotlin Coroutines
Improve app performance with Kotlin coroutines
Further Reading
Compare Kotlin’s Coroutine Launch, Async-Await, or SuspendCancellableCoroutine
What is the difference between launch/join and async/await in Kotlin coroutines