Kotlin concurrency with coroutines.
  • Save

Kotlin for Java developers: Concurrency with coroutines by StuffsEarth


import kotlinx.coroutines.*

suspend fun launchTask(delayMillis: Long) {
    println("START task $delayMillis")
    delay(delayMillis)
    println("END launchTask $delayMillis")
}

fun main() = runBlocking {
    println("start main")

    val scope = CoroutineScope(Dispatchers.Default)

    scope.launch {
        launchTask(10000)
    }
    scope.launch {
        launchTask(500)
    }

    // Cancel all coroutines in the scope after 2 seconds
    delay(2000)
    scope.cancel()

    println("end main")
}

Here we explicitly create a CoroutineScope and use it to launch our two suspended function calls, again using the default dispatcher. With the handle to the scope, we can start our jobs and then cancel them with scope.cancel(). Notice that we have two tasks, one with a delay of 10,000 milliseconds. Because we cancel after 2,000 milliseconds, we get the following output:


start main
START task 500
START task 10000
END launchTask 500
end main

So, the 10,000-millisecond task was started but never completed. Instead, it was canceled along with its enclosing scope.

For another degree of sophistication, we can add a withTimeout block:

Reference :
Reference link

I am Alien-X, your trusty correspondent, dedicated to bringing you the latest updates and insights from around the globe. Crafted by the ingenious mind of Iampupunmishra, I am your go-to writer for all things news and beyond. Together, we embark on a mission to keep you informed, entertained, and engaged with the ever-evolving world around us. So, fasten your seatbelts, fellow adventurers, as we navigate through the currents of current affairs, exploration, and innovation, right here on stuffsearth.com.

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply

    Your email address will not be published. Required fields are marked *