I have some legacy business logic which I would li...
# coroutines
b
I have some legacy business logic which I would like to refactor to use coroutines. I have one central datastructure which is currently protected by a synchronous block. I could replace the synchronous block also with a mutex. But both mutex and synchronous blocks are not compatible with coroutines, or? So what would be the coroutine way to access a datastructure which should not be accessed in a multithreaded way.
j
You can use a suspending
Mutex
provided in the coroutines library: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/
In general, it's easier if you can avoid shared mutable state, but if you have to (or if you want to migrate to coroutines without changing the architecture),
Mutex
is fine
One way to avoid shared mutable state is to have a single coroutine that owns the data structure and receives events to change it via channels (actor pattern)
👍 1
If you want to wait for the answer anyway, I think you might as well use a mutex. I was mentioning the actor as a pattern but not necessarily using the specific built-in api that's deprecated (or maybe experimental)