Async coroutine builder helps you run tasks in the background without stopping your main program. It lets you start work now and get the result later.
0
0
Async coroutine builder in Kotlin
Introduction
When you want to download data from the internet without freezing the app.
When you need to do a long calculation but still keep the app responsive.
When you want to start multiple tasks at the same time and wait for all results.
When you want to improve app speed by doing work in parallel.
When you want to handle tasks that might take time, like reading files or databases.
Syntax
Kotlin
val deferred = async { // some suspend function or long running code } val result = deferred.await()
async starts a coroutine that returns a Deferred object.
You use await() on the Deferred to get the result when ready.
Examples
This example waits 1 second and then returns "Hello".
Kotlin
val deferred = async { delay(1000L) "Hello" } val result = deferred.await()
Starts two tasks at once and adds their results after both finish.
Kotlin
val deferred1 = async { 10 * 10 } val deferred2 = async { 20 + 30 } val sum = deferred1.await() + deferred2.await()
Sample Program
This program starts an async coroutine that waits half a second and returns "Kotlin". Meanwhile, it prints a message. Then it waits for the result and prints it.
Kotlin
import kotlinx.coroutines.* fun main() = runBlocking { val deferred = async { delay(500L) "Kotlin" } println("Waiting for result...") val result = deferred.await() println("Result: $result") }
OutputSuccess
Important Notes
Use async inside a coroutine scope like runBlocking or launch.
Calling await() suspends the current coroutine until the result is ready.
Don't forget to import kotlinx.coroutines.* to use async and await.
Summary
async starts a background task and returns a Deferred result.
Use await() to get the result when it is ready, without blocking the whole program.
This helps keep your app responsive while doing work in the background.