I know this is a recurrent question and Im a bit s...
# coroutines
t
I know this is a recurrent question and Im a bit sorry for asking again but: Q: What is currently the best an simplest way to ensure that a mutable variable is only changed by one coroutine simultaneously? A:
MutableStateFlow
1
t
if you mean cross thread safe updates,
MutableStateFlow.value =
if it’s for during a longer time (e.g. a block)
Mutex
(from coroutines), but if not the above is much simpeler
h
I think the standard way will be to expose mutable interface to only that coroutine. Like I do for my repositories. My repositories implements two interfaces 1. Mutable 2. Immutable All the consumers will be using repository as Immutable Only the Network layer uses mutable version of repository. may be we can provide better answer if you can tell some example use case
t
You can do that MutableStateFlow too (just expose it as StateFlow)
not saying your approach is wrong of course @Hitender Pannu, just that StateFlow is a way to implement that
h
@Tijl correct, Even I use MutableStateFlow inside my Repo Impl, but interface will expose those variables as StateFlow
👌 1
w
You can also use actors
h
actors is something new to me, Sounds interesting do you have some reference I can checkout
j
You can use a mutex and surround modifications & reads to the var with a
mutex.withLock {...}
That will make it thread safe and thus safe against coRoutines running on different threads as well. For single threaded uses, you should not need this.
t
It looks like the solution I was searching for is
MutableStateFlow
it's not marked as
@ObsoleteCoroutinesApi
and does the thing I needed. Also I looked into it Mutex and it seems to be far to low level for my usecase. Thanks guys 👍