How can I cancel a coroutine I started with `start...
# coroutines
s
How can I cancel a coroutine I started with
startCoroutineCancellable
?
a
why do you use
startCoroutineCancellable
?
s
To run a suspend function with a callback instead of a suspension.
I trying building an effect system on top of suspend functions. I almost finished it using only what is in kotlin std but I got stuck with cancellation.
a
You probably should see how it done in
kotlinx.coroutines
s
Where?
s
I meant see how what is done?
a
Cancelation for builders.
s
AFAIK they do so with
Scope
and
Job
but all of that is not available from
startCancellableContinuation
v
startCoroutineCancellable
is internal API and is not intended to be used externally. E.g. it is cancellable only when it is used with interceptor from
kotlinx.coroutines
and when used on instance of
DispatchedContinuation
s
Okay. Is there another way I can achieve this? I frequently use
startCoroutine
to bridge between suspending world and non suspending world but there is no way to take in account cancellation as far as I know.
v
Could you please describe your use-case with a sample of code with the desired behaviour? Maybe there are other ways to do what you want
currently, cancellation is available (publicly) on suspension points when used with
suspendCancellableCoroutine
s
I want to start a given
suspend () -> A
on a given
CoroutineContext
within a
Continuation
.
Copy code
class Fx<A>(val fa: suspend () -> A) {
  ...

  fun startOn(ctx: CoroutineContext): Fx<Fiber<ForFx, A>> =
      Fx {
        val promise = UnsafePromise<A>()
      
        fa.startCoroutine(asyncContinuation(ctx) { either ->
          either.fold(
            { promise.complete(it.left()) },
            { promise.complete(it.right()) }
          )
        })
      
        val cancel: Fx<Unit> = Fx { Unit /* cancel running coroutine */ }

        FxFiber(promise, cancel)
      }
}
val cancel: Fx<Unit> = Fx { Unit /* cancel running coroutine */ }
is the piece of code I am still missing
Fiber is an alias for two actions
Pair(join, cancel)
@Vsevolod Tolstopyatov [JB] basically build this but with cancellation support https://github.com/Kotlin/kotlin-coroutines-examples/blob/master/examples/run/launch.kt