Hi all, does coroutines (or continuations) have so...
# coroutines
b
Hi all, does coroutines (or continuations) have some kind of "hooks" that we can attach to on resume? Basically I want to intercept the resumption of continuations to do some custom behavior before actually resuming. I hope this question makes sense to you.
s
You can run a coroutine with
fun (suspend () -> A).startCoroutine(cont: Continuation<A>)
You can wrap this with the
suspendCoroutine
builder to achieve your use case if I'm not mistaken.
May I ask what your use case is? I wanted to build in some error handling for
Deferred
but was unsuccessful but with regular suspend functions this should work.
b
Hi, thanks. My use case is I want to instrument coroutines with APM. I want to link the separate threads as a single transaction, so I need to call something like
token.link()
on each resume
s
Okay, so excessive wrapping might not be desired then.
b
Yes indeed, ideally I don't have to modify many of the call sites... I'm thinking of overriding/extending ContinuationInterceptor somehow
Btw, could you explain about the startCoroutine + suspendCoroutine? How would it look like?
v
@bobby yes they do! AFAIK the "hooks" are called interceptors and are a central part of coroutine context. Basically, dispatchers and other parts in coroutine context are (were last time I looking into the code) implemented as interceptors. See https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-continuation-interceptor/index.html
b
@voddan thanks! yeah I've also read about
ContinuationInterceptor
and how dispatchers implement that interface. Sadly
interceptContinuation
seems to be
final
in
CoroutineDispatcher
base class so I don't see ways to use it while still using existing dispatchers (default, IO, etc.)
v
I don't think you need to extend coroutine dispatchers. Rather, you could try making something LIKE a coroutine dispatcher using the same mechanics to intersect suspend points