kotlinkotlin-coroutinessuspendcontinuation-passing

How Kotlin coroutine internals decide should function be suspended or result can be returned immediately?


As I understand suspend function transforms to function with additional Continuation parameter and when block from suspendCoroutineUninterceptedOrReturn returning COROUTINE_SUSPENDED value - suspend fun suspends.

But how Kotlin coroutine internals decide should function be suspended or result can be returned immediately?


Solution

  • Marking it suspend gives a function the ability to suspend, but it only suspends if the function itself calls another function that actually suspends. In the standard library, some common functions that suspend are delay(), withContext (which only suspends if it changes dispatchers from the current one), Job.join(), Deferred.await(), SendChannel.send(), ReceiveChannel.receive(), Flow.collect(), suspendCoroutine, and suspendCancellableCoroutine. Some of these suspend only under certain conditions

    If you look at the source code of the above functions, they are pretty low level and mess with the Continuation directly or have intrinsic behaviors.

    I might have missed some of these base level suspend functions, but it generally comes down to whether one of them is in the call stack and hits a condition where it suspends.