Dontsu
09/19/2023, 1:35 AMKotlin Coroutines deep dive
by Marcin Moskala
.
In the part of understanding Kotlin Coroutine
of the book(specifically, How does suspension work?
), I read this code below.
suspend fun main() {
println("Before")
suspendCoroutine<Unit> { continuation ->
continuation.resume(Unit)
}
println("After")
}
// Before
// After
Notice that “After” in the example above is printed because we call
resume in suspendCoroutine. This statement is true, but I need to clarify. You might imagine
that here we suspend and immediately resume. This is a good intuition, but the truth is that there is an optimization that prevents a suspension if resuming is immediate.Speaking of the
optimization
, in this case, Does it mean that "There is no suspension point in the Coroutine. So, there is no need to be suspended. That's why the compiler optimizes."??
For instances,
1)
suspend fun getUsers(): List<User> {
// no asynchronous work and suspension point here
// ....
return users
}
in the code above, the IDE informs me that I don't need to use "suspend"(Redundant 'suspend' modifier). So, it also would be an optimazation.
2)
suspend fun getUsers(): List<User> {
suspendCoroutine<Unit> { continuation -> // this code line is definitely a suspention point.
// list sorting or something but not asynchronous work.
continuation.resume(Unit)
}
return users
}
in the code above, it's almost same code of the example of the book. but i wonder how the compiler optimizes the code under the hood.
and I wonder if there are any other optimizations for susepnd
. i hope someone tells me about it.xoangon
09/19/2023, 6:14 AMDontsu
09/19/2023, 6:54 AMPatrick Steiger
09/24/2023, 12:51 AMsuspendCoroutineUninterceptedOrReturn
. Note the OrReturn
. That means this call will either return some value immediately, or COROUTINE_SUSPENDED
token. If this function never returns the suspended token, code transformation into a state machine would also not be needed, but I’m not sure if compiler is that smart to detect this caseDontsu
10/25/2023, 4:31 AM