So i have a to implement a Java interface to do so...
# coroutines
e
So i have a to implement a Java interface to do some logic. My implementation uses corutines, and my code triggering the library uses corutine. How can i pass the scope past the interface... Now i have runBlocking in the interface but it brakes the context and the tracing
b
Pass it via constructor?
e
Do not work whit the interface structure. I do not control the interface as its from a package
s
But you do control the implementation of the interface. You can provide a CoroutineScope to the implementation's constructor.
e
I was unshure that would be the right scope or the scope is was created and not called
j
It also depends on what the Java interface's contract is. If the contract is to finish the work before returning (which is for instance the case when you need to actually return a value synchronously), then you have no choice but to block the thread until the work is done, so you'll need
runBlocking
in a way. If the Java interface is asynchronous (for instance with a callback or returning a
Future
then it's another story, but I doubt you would have those questions if it were the case.
Now, even if you do use
runBlocking
, you can still customize the coroutine context (not the scope), by passing the context as a constructor argument to your Kotlin implementation of the Java interface. That being said, you won't be able to pass the context from the caller of the methods of that interface to the implementation of the interface. EDIT: I was wrong on this, see below
e
did not managed to get context that had the tracing to pass on. But looks like i was able to manage to get context from the java Thread and use it in runBlocking
j
ah yes you might be able to pass it through the thread's context indeed, well done
e
Yes looks like the way
j
did you use a
ThreadLocal
for this? or some kind of MDC library?
e
It's a OpenTelemetry implementation using the Java library. Kind of a pain tracing trough corutines and the having some java in between. I think it more of a MDC kind of library.