Coroutines Concepts
Cancellation Flag Model
Real coroutine cancellation is cooperative; this static example models the same idea with a checked flag.
Cancellation Flag Model
CancellationFlagModel.kt
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.startCoroutine
suspend fun runStep(active: Boolean, name: String): String {
return if (active) "ran:$name" else "skipped:$name"
}
fun main() {
val active =
val log = mutableListOf<String>()
val work: suspend () -> String = {
log.add(runStep(active, "load"))
log.add(runStep(active, "save"))
log.joinToString("|")
}
work.startCoroutine(object : Continuation<String> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<String>) {
log.add("done")
}
})
println("active=$active")
println("log=" + log.joinToString("|"))
}
import kotlin.coroutines.Continuation
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.startCoroutine
suspend fun runStep(active: Boolean, name: String): String {
return if (active) "ran:$name" else "skipped:$name"
}
fun main() {
val active =
val log = mutableListOf<String>()
val work: suspend () -> String = {
log.add(runStep(active, "load"))
log.add(runStep(active, "save"))
log.joinToString("|")
}
work.startCoroutine(object : Continuation<String> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<String>) {
log.add("done")
}
})
println("active=$active")
println("log=" + log.joinToString("|"))
}
cooperative cancellation
Cooperative code checks whether it should continue before doing the next unit of work.