I have tried the following code:
This is the simplest … If am not mistaken, this should print
about to block
in runBlocking - before calls
in runBlocking - after test1()
inside init
in runBlocking - after test2()
done
But, it never reaches the line
println(“inside init”)
and it blocks forever.
This is reproducible with all versions of the Kotlin compiler that creates JVM bytecode, both in the Playfield, and also in Android Studio
This makes coroutines completely useless!!
I could be wrong, but this seems to be a COMPILER BUG, AND A VERY SERIOUS ONE!
Please, correct me if I am wrong…
You had accidentally surrounded the code inside suspendCoroutine
in a lambda. Here’s the fixed version:
import kotlin.coroutines.suspendCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.runBlocking
suspend fun test1() : Boolean {
delay(10)
return true
}
suspend fun test2() : Boolean = suspendCoroutine { continuation ->
println("inside init")
continuation.resume(false)
}
fun main() {
println("about to block")
runBlocking {
println("in runBlocking - before calls")
test1()
println("in runBlocking - after test1()")
test2()
println("in runBlocking - after test2()")
}
println("done")
}
The compiler even gave you a warning about an unused expression btw
2 Likes
Thanks a lot. I even decompiled the bytecode, and it was very strange that a lambda with the code was there, but was unused…
Android Studio does not report that warning (I cannot find it anywhere!), and the Playground does not show the warning. I guess the only way to get it would be to run an standalone compiler from the command line.
Again, thanks for your time and patience!
2 Likes