Gilles Barbier
03/11/2021, 10:20 AMrunBlocking {
launch {
println("a1")
runBlocking { delay(100) }
println("b1")
}
launch {
println("a2")
runBlocking { delay(300) }
println("b2")
}
}
displays a1 a2 b2 b1 - instead of a1 a2 b1 b2lewis
03/11/2021, 10:54 AMrunBlocking
will schedule a coroutine using CoroutineStart.DEFAULT
which is effectively "immediately" - meaning the coroutine scheduled last will execute first.uli
03/11/2021, 10:54 AMrunBlocking { delay
that happens to start. if this would be your `runBlocking { delay(300) }`then it blocks the second, shorter deelay from even startinglewis
03/11/2021, 10:55 AMrunBlocking
inside a suspend function in real code?Thread.sleep
yields the expected results as there's no additional scheduling at play.Gilles Barbier
03/11/2021, 10:58 AMuli
03/11/2021, 10:59 AMGilles Barbier
03/11/2021, 10:59 AMuli
03/11/2021, 11:03 AMlaunch(Dispatchers.Default)
wil solve your imediate problem. But is more like a band Aid here:
https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjQxIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncy[…]AgICAgcHJpbnRsbihcImIyXCIpXG4gICAgICAgIH1cbiAgICB9XG59In0=async
and Deferred.asCompletableFuture
to return a completable future instead of blocking:
https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-jdk8/kotlinx.coroutine[…]ture/kotlinx.coroutines.-deferred/as-completable-future.htmlmyanmarking
03/11/2021, 3:06 PMOrhan Tozan
03/11/2021, 6:40 PMuli
03/11/2021, 6:49 PMOrhan Tozan
03/11/2021, 6:52 PMuli
03/11/2021, 6:56 PMmyanmarking
03/11/2021, 6:57 PMuli
03/11/2021, 6:57 PMOrhan Tozan
03/11/2021, 6:58 PMuli
03/11/2021, 6:59 PMmyanmarking
03/11/2021, 6:59 PMuli
03/11/2021, 7:02 PMmyanmarking
03/11/2021, 7:03 PMuli
03/11/2021, 7:39 PMrunBlocking { delay(300) }
is basically like Thread.sleep(300)myanmarking
03/12/2021, 12:53 AMuli
03/12/2021, 8:12 AMmyanmarking
03/12/2021, 10:09 AMuli
03/12/2021, 10:14 AMb1
myanmarking
03/12/2021, 10:15 AMuli
03/12/2021, 10:25 AMmyanmarking
03/12/2021, 10:32 AMuli
03/12/2021, 10:37 AMdelay
myanmarking
03/12/2021, 10:40 AMGilles Barbier
03/12/2021, 11:33 AMuli
03/12/2021, 11:36 AMrunBlocking
behaviour, replace runBlocking {delay(100)}
in your tests with Thread.sleep(100)
myanmarking
03/12/2021, 11:38 AMGilles Barbier
03/12/2021, 4:23 PMuli
03/12/2021, 4:46 PMlaunch
start two concurrent coroutines. Because they don’t suspend though, they are not interleaved on a single threaded dispatcher.