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

hmole

06/26/2019, 5:09 AM
I'm trying to start cancellable(synchroniously) async operation inside a suspend function(without
CoroutineScope
receiver). Is there a better way? Sample in a thread.
Copy code
private suspend fun <T> Call<T>.executeAsync(): Response<T> {
  val call = this
  return suspendCancellableCoroutine { continuation ->

    continuation.invokeOnCancellation { call.cancel() }
    
    CoroutineScope(continuation.context).launch {
      val result = runCatching(call::execute)
      continuation.resumeWith(result)
    }
  }
}
s

streetsofboston

06/26/2019, 5:59 AM
Since you're in the body of a
suspend
function, you can call the function called
coroutineScope
and call
launch
from within its lambda. However, since
coroutineScope
waits/suspends until all it's children have finished (including this
launch
) and you need a result, why not just use a more simple 'async { }' with 'await()' and listen to the completion/cancellation of the Job (Deferred) returned by this 'async' call? No
suspendCancellableCoroutine
and no coroutine-scope.
h

hmole

06/26/2019, 6:04 AM
invokeOnCompletion
is not synchronious(I know docs say it is, but it's not(at least in my case)) cancellation, so I can't use that.
l

louiscad

06/26/2019, 10:27 AM
If you observe something different from what the doc sayd, then it's a bug to report here: https://github.com/Kotlin/kotlinx.coroutines/issues/new
s

streetsofboston

06/26/2019, 11:13 AM
@hmole By examining
cause
you can check whether the job just ended or ended with an exception or cancellation. https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/invoke-on-completion.html
3 Views