Coroutines Concepts
Continuation Result
A continuation receives success or failure through a Result value.
Continuation Result
ContinuationResult.kt
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.startCoroutine
suspend fun parsePositive(text: String): Int {
val number = text.toInt()
if (number <= 0) {
error("not positive")
}
return number
}
fun main() {
val text =
var summary = "not resumed"
val work: suspend () -> Int = {
parsePositive(text)
}
work.startCoroutine(object : Continuation<Int> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<Int>) {
summary = result.fold(
onSuccess = { value -> "success=$value" },
onFailure = { error -> "failure=${error.message}" }
)
}
})
println(summary)
}
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.startCoroutine
suspend fun parsePositive(text: String): Int {
val number = text.toInt()
if (number <= 0) {
error("not positive")
}
return number
}
fun main() {
val text =
var summary = "not resumed"
val work: suspend () -> Int = {
parsePositive(text)
}
work.startCoroutine(object : Continuation<Int> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<Int>) {
summary = result.fold(
onSuccess = { value -> "success=$value" },
onFailure = { error -> "failure=${error.message}" }
)
}
})
println(summary)
}
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.startCoroutine
suspend fun parsePositive(text: String): Int {
val number = text.toInt()
if (number <= 0) {
error("not positive")
}
return number
}
fun main() {
val text =
var summary = "not resumed"
val work: suspend () -> Int = {
parsePositive(text)
}
work.startCoroutine(object : Continuation<Int> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<Int>) {
summary = result.fold(
onSuccess = { value -> "success=$value" },
onFailure = { error -> "failure=${error.message}" }
)
}
})
println(summary)
}
continuation result
`Result` lets the continuation handle a produced value or an exception without changing the callback shape.