https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

paulblessing

03/27/2019, 2:42 PM
Is there a suggested approach to cooperative cancellation when calling into code from a coroutine that may not know or care that it's executing inside of a coroutine? The best thought I had was to pass along a facade around the
Job
.
Copy code
interface ActiveIndicator {
  val isActive: Boolean
  fun ensureActive()
}

private class JobActiveIndicator(private val job: Job) : ActiveIndicator {

  override val isActive: Boolean get() = job.isActive

  override fun ensureActive() {
    job.ensureActive()
  }

}

suspend fun doSomething() {
  val job = coroutineContext[Job]!!
  executeCancellableTask(JobActiveIndicator(job))
}

// (Possibly even in Java code somewhere)
fun executeCancellableTask(activeIndicator: ActiveIndicator) {
  while (activeIndicator.isActive) {
    // Do some work
  }
}
e

elizarov

03/27/2019, 2:44 PM
Yes. You can pass a
Job
as a “cancellation token” to support cancellation in the otherwise non-coroutines code.
👍 1
2 Views