launch / async
In Kotlin coroutines, launch is used to start a concurrent operation that does not return a result, while async is used to start one that does. Both run asynchronously within a CoroutineScope.
Syntax
// launch — no result (returns a Job)
val job: Job = scope.launch {
// Async operation (no return value)
}
job.join() // Suspend until complete
// async — with result (returns Deferred<T>)
val deferred: Deferred<String> = scope.async {
"result" // Return value
}
val result = deferred.await() // Retrieve result (suspends)
Syntax Reference
| Function | Description |
|---|---|
| launch { } | Starts a coroutine that does not return a result. Returns a Job. |
| async { } | Starts a coroutine that returns a result. Returns a Deferred<T>. |
| job.join() | Suspends the current coroutine until the Job completes. |
| job.cancel() | Cancels the Job. |
| deferred.await() | Suspends the current coroutine until the Deferred produces a result. |
| Dispatchers.IO | Runs the coroutine on a thread pool optimized for I/O operations. |
| Dispatchers.Default | Runs the coroutine on a thread pool optimized for CPU-intensive work. |
Sample Code
import kotlinx.coroutines.*
fun main() = runBlocking {
// launch — concurrent operation with no return value
val job1 = launch {
delay(300)
println("job1 done")
}
val job2 = launch {
delay(100)
println("job2 done")
}
job1.join() // Wait for job1 to complete.
job2.join()
// Output order: job2 done (first), job1 done (second).
// async — concurrent operation with a return value (runs in parallel)
val deferred1 = async {
delay(200)
"Result A"
}
val deferred2 = async {
delay(100)
"Result B"
}
// Run both concurrently and collect results together.
println("${deferred1.await()}, ${deferred2.await()}")
// Result A, Result B (completes in ~200ms)
// Run an I/O operation on a separate thread using Dispatchers.IO.
val ioResult = async(Dispatchers.IO) {
// Perform file reads or network calls here.
"IO result"
}
println(ioResult.await()) // IO result
}
Notes
The choice between launch and async depends on whether you need a return value. Use launch when no result is needed, and async with await() when you want to retrieve one.
A common pattern is to start multiple async coroutines concurrently and call await() on all of them afterward. Calling await() immediately after each async results in sequential execution; starting them all first and awaiting later enables true parallel execution.
For defining suspendable functions, see suspend functions. For waiting and timeouts, see delay() / withTimeout().
If you find any errors or copyright issues, please contact us.