Hi guys, I have some libraries that use ThreadLoca...
# coroutines
a
Hi guys, I have some libraries that use ThreadLocal in my application and I’m using the
.asContextElement()
extension function to make them coroutine-ready. All works well but i find my code having something like this
Copy code
launch(object1.asContextElement() + object2.asContextElement()) {}
I was thinking to encapsulate those element into a container such that I can do something like this
Copy code
launch(myContext) {}
where
mycontext
contains the elements from object1 and object2. I was thinking to do this by implementing the
CoroutineContext
interface but I then I need to implement all its functions, while what I really want is just the default
+
behavior. Is there any nice way to achieve this?
e
Copy code
val myContext = object1.asContextElement() + object2.asContextElement()
a
yes, thanks Roman, but I wanted to use dependency injection and box the 2 elements into a single “context”
e
Cannot you inject a value? What DI framework do you use?
a
Spring
e
Anyway, if you cannot, you can do
Copy code
object MyContext: CoroutineContext by (object1.asContextElement() + object2.asContextElement())
a
can’t inject the value directly since the singleton I’m in it’s going to have different values for different requests
object MyContext: CoroutineContext by (object1.asContextElement() + object2.asContextElement())
this is amazing, will try this one. let me see if I can make it working with DI
K 3
thanks a lot! I knew there was a more elegant way!