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

simon.vergauwen

02/04/2019, 1:25 PM
How can I cancel a coroutine I started with
startCoroutineCancellable
?
a

altavir

02/04/2019, 1:30 PM
why do you use
startCoroutineCancellable
?
s

simon.vergauwen

02/04/2019, 1:32 PM
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

altavir

02/04/2019, 1:35 PM
You probably should see how it done in
kotlinx.coroutines
s

simon.vergauwen

02/04/2019, 1:35 PM
Where?
s

simon.vergauwen

02/04/2019, 1:36 PM
I meant see how what is done?
a

altavir

02/04/2019, 1:37 PM
Cancelation for builders.
s

simon.vergauwen

02/04/2019, 1:38 PM
AFAIK they do so with
Scope
and
Job
but all of that is not available from
startCancellableContinuation
v

Vsevolod Tolstopyatov [JB]

02/04/2019, 1:56 PM
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

simon.vergauwen

02/04/2019, 1:57 PM
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

Vsevolod Tolstopyatov [JB]

02/04/2019, 1:57 PM
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

simon.vergauwen

02/04/2019, 2:03 PM
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
4 Views