Sobes.tech
Junior — Middle

How to implement waiting for the completion of a task launched with launch in a coroutine?

sobes.tech AI

Answer from AI

In Kotlin, to wait for the completion of a task launched with launch, you need to keep a reference to the Job object returned by the launch function and call its join() method. This will suspend the current coroutine until the launched task completes.

Example:

val job = CoroutineScope(Dispatchers.Default).launch {
    // Some asynchronous work
    delay(1000L)
    println("Task completed")
}

runBlocking {
    job.join() // Wait for the task to complete
    println("Continuing after completion")
}

Thus, join() allows synchronizing execution and waiting for the coroutine launched via launch to finish.