Sobes.tech
Junior — Middle

How to organize waiting for the completion of coroutine execution in an asynchronous program?

sobes.tech AI

Answer from AI

To wait for the completion of coroutines in Kotlin, the join() function is usually used on the Job object, which is returned when a coroutine is launched. If a coroutine is launched via launch, it returns a Job, and calling job.join() suspends the current thread until the coroutine completes.

Example:

val job = GlobalScope.launch {
    // some asynchronous work
    delay(1000)
    println("Coroutine finished")
}

runBlocking {
    job.join() // wait for the coroutine to finish
    println("Coroutine has completed")
}

If async is used, then await() is used to get the result and wait for the coroutine to finish.

val deferred = GlobalScope.async {
    delay(1000)
    return@async 42
}

runBlocking {
    val result = deferred.await() // wait and get the result
    println("Result: $result")
}