...

/

Resuming with a Value

Resuming with a Value

Learn how to resume a suspended coroutine with a value.

We'll cover the following...

One thing that might concern us is why we passed Unit to the resume function. We might also be wondering why we used Unit as a type argument for the suspendCoroutine. The fact that these two are the same is no coincidence. The Unit parameter is also returned from the function and is the generic type of the Continuation parameter.

Press + to interact
val ret: Unit =
suspendCoroutine<Unit> { cont: Continuation<Unit> ->
cont.resume(Unit)
}

When we call suspendCoroutine, we can specify which type will be returned in its continuation. The same type needs to be used when we call resume. Let's look at an example and run this code.

package kotlinx.coroutines.app
import kotlin.coroutines.*

suspend fun main() {
   val i: Int = suspendCoroutine<Int> { cont ->
       cont.resume(42)
   }
   println(i)

   val str: String = suspendCoroutine<String> { cont ->
       cont.resume("Some text")
   }
   println(str)

   val b: Boolean = suspendCoroutine<Boolean> { cont ->
       cont.resume(true)
   }
   println(b)
}
Suspend coroutine with specified return type

Game analogy

...