Launch vs Async in Kotlin Coroutines
In this blog we will learn about when we want to use coroutines for networking/suspending functions. There are 2 approaches.
- Use launch
- Use async-await
Difference between them is what we will be looking into.
Launch vs Async-await
Launch is fire and forget
Launch is when you launch a coroutine without blocking the current thread and returns a reference to the coroutine as Job. Using this reference, Job status can be checked as per requirement. The coroutine is cancelled when the resulting job is cancelled.
Async-await returns a result.
Async-await is when you create a coroutine and returns its future result as an implementation of Deferred object. Using this deferred object await() can be called which returns the result. The running coroutine is cancelled when the resulting deferred is cancelled.
Let’s take an look with help of an example -
val job = CoroutineScope(Dispatchers.Default).launch {
//TODO suspend any call.
}
In the above example only job is returned.
Job’s status can be checked via
job.isActive
Job’s can be cancelled via
job.cancel()
Cancelling of the job might be required if you want to explicitly cancel the coroutine/when the lifecycle of the coroutine is handled by the user itself.
Next,
let’s look at async-await example -
val deferred = CoroutineScope(Dispatchers.Default).async {
//suspend function with deferred instance
return@async true
}
In the above example deferred instance is returned. When await is called on this, result of the coroutine is returned.
val result = deferred.await()
Advantages of async-await over launch is that it can be used to do multiple parallel network calls.
Error — Handling
If there happens to be an error in launch then the application crashes if it is not handled. Handling it is pretty easy with try-catch block.
CoroutineScope(Dispatchers.Default).launch {
try {
//do something that might throw error
} catch (e: Exception) {
}
}
In async-await scenario error is handled by the Deferred object. The error is actually swallowed silently if try-catch block is missing. If try-catch block is used then error is propagated to catch block and can be handled by user.
CoroutineScope(Dispatchers.Default).async {
try {
//do something that might throw error
} catch (e: Exception) {
//handle exception
}
}
So, we have understood the difference between the launch function and the async function.
That’s all for now. Thanks.
Please feel free to reach out to me on LinkedIn.