kotlin coroutine invoke completion
import kotlinx.coroutines.*
fun main() {
val job = GlobalScope.launch {
println("Coroutine started")
delay(1000)
println("Coroutine completed")
}
job.invokeOnCompletion { throwable ->
if (throwable != null) {
println("Coroutine failed: $throwable")
} else {
println("Coroutine completed successfully")
}
}
Thread.sleep(2000)
}
This Kotlin code demonstrates the use of coroutines and invokeOnCompletion
to handle the completion or failure of a coroutine. Here's a breakdown of the steps:
import kotlinx.coroutines.*
: Import necessary coroutine-related classes and functions.fun main() { ... }
: Entry point of the program. Inside the main function:val job = GlobalScope.launch { ... }
: Launches a new coroutine in the global scope. This coroutine prints a message, suspends execution for 1000 milliseconds usingdelay
, and then prints another message. The returnedJob
objectjob
represents the coroutine.job.invokeOnCompletion { throwable -> ... }
: Attaches aninvokeOnCompletion
block to thejob
to handle its completion. If an exception occurred during the coroutine's execution, thethrowable
parameter will contain the exception. The block checks if an exception occurred or if the coroutine completed successfully and prints corresponding messages.Thread.sleep(2000)
: The main thread pauses for 2000 milliseconds to keep the program running while the coroutine initiated byGlobalScope.launch
has time to complete.
This code essentially demonstrates how to use invokeOnCompletion
to handle the completion or failure of a coroutine launched using Kotlin coroutines.