Scott Kruse
01/06/2023, 7:35 PMdelay(500L)
but will intermittently work with delay(499L)
or shorter durations?
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS44LjAiLCJwbGF0Zm9ybSI6ImphdmEiLCJhcmdzIj[…]AgICAgICAgIHByaW50bG4oZSlcbiAgICAgIH1cbiAgfSAgIFxufVxuIn0=
code in thread as wellScott Kruse
01/06/2023, 7:35 PM/**
* You can edit, run, and share this code.
* <http://play.kotlinlang.org|play.kotlinlang.org>
*/
import kotlinx.coroutines.*
private var job: Job? = null
private var scope = CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
val handler = CoroutineExceptionHandler { _, exception ->
println("CoroutineExceptionHandler got $exception")
}
fun main() {
test("1")
test("2")
test("3")
}
fun test(label: String) {
job?.cancel()
job = scope.launch(handler) {
try {
println("starting")
delay(500L)
println(label)
} catch (e: Exception) {
println(e)
}
}
}
Landry Norris
01/06/2023, 7:44 PMrunBlocking {
delay(1000)
}
to the end, and it works every time.ephemient
01/06/2023, 7:46 PMcoroutineScope
or similar so that you can properly await all active jobsephemient
01/06/2023, 7:47 PMsuspend fun main(): Unit = coroutineScope {
test("1")
test("2")
test("3")
}
fun CoroutineScope.test(label: String) {
job?.cancel()
job = launch(handler) {
try {
println("starting")
delay(500L)
println(label)
} catch (e: Exception) {
println(e)
}
}
}
Scott Kruse
01/06/2023, 7:58 PMLandry Norris
01/06/2023, 7:58 PMLandry Norris
01/06/2023, 7:59 PMephemient
01/06/2023, 8:00 PM<http://Dispatchers.IO|Dispatchers.IO>
and the other built-in dispatchers are run on a pool of daemon threads, so they do not prevent the JVM from shutting down when main
returnsCLOVIS
01/07/2023, 11:39 AMJoffrey
01/07/2023, 3:48 PMdelay is blocking, but it blocks the current coroutineThis is not the vocabulary used in this case. Blocking specifically means blocking a thread, Suspending means the current coroutine stops its execution, but the thread that was executing it is now free to do something else.
Landry Norris
01/07/2023, 3:53 PMlouiscad
01/09/2023, 6:46 PMlouiscad
01/09/2023, 6:47 PMLandry Norris
01/09/2023, 6:48 PMCLOVIS
01/09/2023, 6:49 PMCLOVIS
01/09/2023, 6:50 PM