Kevin M Granger
12/01/2020, 5:47 PMsuspend fun
out of a home-grown coroutine?
Suppose I have some computation-heavy code that has some natural "pause" points. I'd like to use existing coroutine tools to handle cancellation and timeouts-- but everything expects you to use a suspend
function.
In other words, I more or less have this:
sealed class ComputationResult {
abstract fun finish(): Int
class Finished(val result: Int) : ComputationResult() {
overide fun finish() = result
}
class InProgress(val rest: Computation) : ComputationResult() {
override fun finish() = rest().finish()
}
}
// does not currently implement Continuation<Unit> but could easily do so
class Computation {
operator fun invoke(): ComputationResult {
TODO()
// implementation elided here, but it could easily check
// to see if it was cancelled
}
}
Can I turn it into suspend fun compute() -> Int
?invoke
or finish
a suspend fun, and use plain 'ol yield
, but I'm wondering if there's a better wayZach Klippenstein (he/him) [MOD]
12/01/2020, 6:02 PMJob
from your CoroutineContext
and call ensureActive()
on it periodically.Kevin M Granger
12/01/2020, 6:12 PM