https://kotlinlang.org logo
Title
b

bobby

01/23/2019, 11:30 AM
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

simon.vergauwen

01/23/2019, 11:34 AM
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

bobby

01/23/2019, 11:58 AM
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

simon.vergauwen

01/23/2019, 12:00 PM
Okay, so excessive wrapping might not be desired then.
b

bobby

01/23/2019, 12:01 PM
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

voddan

01/24/2019, 10:13 AM
@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

bobby

01/24/2019, 11:59 AM
@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

voddan

01/24/2019, 12:11 PM
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