Search⌘ K
AI Features

Resuming with a Value

Explore how Kotlin coroutines resume with a value, enabling asynchronous operations to wait for data without blocking threads. Understand the role of suspendCoroutine, continuations, and error handling in managing suspended functions. This lesson guides you through practical examples and explains best practices for resuming coroutines with data or exceptions.

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.

Kotlin 1.5
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

...