Hi I'm trying to create a native implementation of...
# coroutines
a
Hi I'm trying to create a native implementation of a coroutine (
native suspend fun
) in rust via JNI. I've managed to create a function which starts an async rust fn in another thread and immediately returns
COROUTINE_SUSPENDED
to kotlin. The question is: Does
resumeWith
run in the native thread (Does is treat the native thread as a dispatcher) or dispatch back to the kotlin dispatcher? I'm using a single thread to call resumeWith as setting up and tearing down JNI Threads are expensive and I would like to know whether its cheap or if it could end up starving other calls to resumeWith? Should I be using a dynamic blocking threadpool to call resumeWith? See for rust code example: https://github.com/mehmooda/suspendlib/blob/main/src/lib.rs
s
This depends on whether the continuation is intercepted or not. A continuation that you receive from an existing coroutine will already be intercepted using the dispatcher (or other continuation interceptor) from the coroutine’s context. A continuation that has been intercepted by a dispatcher will resume on that dispatcher. An unintercepted continuation will resume directly on the thread that called
resumeWith
.
Generally you can assume that if someone’s calling your suspend function in a “normal” way, the continuation will already be intercepted 👍.
So I would say that if someone does manage to call your function with an unintercepted continuation (or chooses to use something like
Dispatchers.UNCONFINED
), that’s their problem, not yours 😄
a
That's good to know. Now all that's left is to set up cancellation notification. Which brings about my second question do I need to handle cancelled exception when calling resumeWith?. The docs don't mention any exceptions but maybe I'm missing it
s
The
resumeWith
method is a no-op if the continuation was already cancelled. (It’s an error if the continuation already resumed, though). Docs: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellable-continuation/