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:
- Using Job — the coroutine returns a Job object, which has a property
isCompleted. If it istrue, then the coroutine has finished.
val job = launch {
// coroutine code
}
// Check
if (job.isCompleted) {
println("Coroutine is completed")
}
-
Using
join()— you can calljob.join()to suspend the current thread until the coroutine completes. -
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")
}
}
- For functions with
async— you can get the result viaawait(), which will complete when the coroutine finishes.