Is there a way to create a `suspend fun` out of a ...
# coroutines
k
Is there a way to create a
suspend 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:
Copy code
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
?
I suppose I could just make
invoke
or
finish
a suspend fun, and use plain 'ol
yield
, but I'm wondering if there's a better way
z
if you just want to check for cancellation, you can pass in the
Job
from your
CoroutineContext
and call
ensureActive()
on it periodically.
k
Hmm, that's an idea. Thanks!