https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Andrea Giuliano

09/03/2020, 2:38 PM
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

elizarov

09/03/2020, 2:40 PM
Copy code
val myContext = object1.asContextElement() + object2.asContextElement()
a

Andrea Giuliano

09/03/2020, 2:41 PM
yes, thanks Roman, but I wanted to use dependency injection and box the 2 elements into a single “context”
e

elizarov

09/03/2020, 2:41 PM
Cannot you inject a value? What DI framework do you use?
a

Andrea Giuliano

09/03/2020, 2:41 PM
Spring
e

elizarov

09/03/2020, 2:42 PM
Anyway, if you cannot, you can do
Copy code
object MyContext: CoroutineContext by (object1.asContextElement() + object2.asContextElement())
a

Andrea Giuliano

09/03/2020, 2:42 PM
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!
2 Views