0
0
Android Kotlinmobile~5 mins

launch and async builders in Android Kotlin

Choose your learning style9 modes available
Introduction

We use launch and async builders to run tasks in the background without freezing the app. This helps keep the app smooth and responsive.

When you want to do a task like loading data from the internet without stopping the app.
When you need to run multiple tasks at the same time and wait for their results.
When you want to update the UI after a background task finishes.
When you want to avoid blocking the main thread with long operations.
Syntax
Android Kotlin
launch {
    // code to run in background
}

val deferred = async {
    // code that returns a result
}
val result = deferred.await()

launch runs a task without returning a result.

async runs a task and returns a Deferred result you can wait for with await().

Examples
This runs a task in the background and prints a message.
Android Kotlin
launch {
    println("Running in background")
}
This runs a task that calculates 5 + 5 and waits for the result to print it.
Android Kotlin
val deferred = async {
    5 + 5
}
val result = deferred.await()
println(result)
Sample App

This program runs a background task with launch that prints after 1 second. It also runs an async task that returns 42 after 0.5 seconds. The main function waits for the async result and prints it.

Android Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    launch {
        delay(1000L)
        println("Task from launch")
    }

    val deferred = async {
        delay(500L)
        42
    }

    println("Waiting for async result...")
    val result = deferred.await()
    println("Result is $result")
}
OutputSuccess
Important Notes

Use launch when you don't need a result back.

Use async when you want to get a result from the background task.

Always call await() on Deferred to get the result and wait for completion.

Summary

launch runs background code without returning a value.

async runs background code and returns a result you can wait for.

Both help keep your app smooth by not blocking the main thread.