Sobes.tech
Junior — Middle

How can you determine that a coroutine has finished execution?

sobes.tech AI

Answer from AI

There are several ways to determine that a coroutine has finished executing:

  1. Using Job — the coroutine returns a Job object, which has a property isCompleted. If it is true, then the coroutine has finished.
val job = launch {
    // coroutine code
}

// Check
if (job.isCompleted) {
    println("Coroutine is completed")
}
  1. Using join() — you can call job.join() to suspend the current thread until the coroutine completes.

  2. Using invokeOnCompletion — you can register a handler that will be called upon the coroutine's completion.

job.invokeOnCompletion { throwable ->
    if (throwable == null) {
        println("Coroutine completed successfully")
    } else {
        println("Coroutine finished with an error: $throwable")
    }
}
  1. For functions with async — you can get the result via await(), which will complete when the coroutine finishes.