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:

  1. import kotlinx.coroutines.*: Import necessary coroutine-related classes and functions.

  2. fun main() { ... }: Entry point of the program. Inside the main function:

  3. val job = GlobalScope.launch { ... }: Launches a new coroutine in the global scope. This coroutine prints a message, suspends execution for 1000 milliseconds using delay, and then prints another message. The returned Job object job represents the coroutine.

  4. job.invokeOnCompletion { throwable -> ... }: Attaches an invokeOnCompletion block to the job to handle its completion. If an exception occurred during the coroutine's execution, the throwable parameter will contain the exception. The block checks if an exception occurred or if the coroutine completed successfully and prints corresponding messages.

  5. Thread.sleep(2000): The main thread pauses for 2000 milliseconds to keep the program running while the coroutine initiated by GlobalScope.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.