Sobes.tech
Junior — Middle

What is the difference between using asynchronous functions with the keyword async and calling launch in asynchronous programming?

sobes.tech AI

Answer from AI

The keyword async is used to declare an asynchronous function that returns an object of type Deferred or Job and can be suspended using suspend functions inside. Calling such a function does not start its execution automatically but returns a deferred result that can be obtained using await.

launch is a function that starts a new coroutine and begins its execution immediately. It returns a Job object, which can be used to manage the coroutine's lifecycle (e.g., cancellation).

Example:

suspend fun fetchData(): String {
    delay(1000)
    return "Data"
}

fun main() = runBlocking {
    // async returns a Deferred, execution starts immediately
    val deferred = async { fetchData() }
    println("Doing other work")
    val result = deferred.await() // wait for the result
    println(result)

    // launch starts a coroutine but does not return a result
    val job = launch {
        val data = fetchData()
        println(data)
    }
    job.join() // wait for completion
}

In summary:

  • async is used to start an asynchronous operation with a return value.
  • launch starts a coroutine without a return value, for background tasks.
  • async returns Deferred, launchJob."}]}]}