Hi all. I’ve got a `CoroutineScope` that works off...
# coroutines
a
Hi all. I’ve got a
CoroutineScope
that works off an IO dispatcher (
<http://Dispatchers.IO|Dispatchers.IO>
) and now I’d need to use a class from an external library that is not thread-safe and requires a heavy initialization phase (in the order of a few seconds) per thread. How should I approach this problem? Would I simply initialize one instance and add it to the current
CoroutineContext
? How would its access be regulated to make sure there is no concurrent multi-thread access from the various coroutines spread across multiple threads (I assume
<http://Dispatchers.IO|Dispatchers.IO>
spans across multiple threads). Any help appreciated.
I could use a
ThreadLocal
-based initialization but I’d be interested in a more idiomatic coroutine-ish approach
a
k
Some of that documentation appears a bit dated, if you're looking for a more idiomatic approach, and you control access to the library, you may be able to convert the data you need from that object into a
flow
, perhaps by using a
BroadcastChannel
for communication. Meaning, you would send messages into the channel and then consume them as a flow, wherever needed.
a
Not sure if
flow
applies in this case. My main constraint is that I have to be sure a different instance of this library has been initialized per thread. Once that’s done, I should be able to use it safely from any coroutine. So basically, every time my coroutine starts or resumes I have to make sure the library instance being used has been initialized.
k
Sounds like an interesting use case. If each of those instances is a source of data, then perhaps each could emit values into streams and then you can apply operations to those streams. If so, then flows may help. It kind of depends on how your data "flows" . . . no pun intended. Wait. Nevermind, pun definitely intended. 🙂
😂 1