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

TheMrCodes

03/30/2021, 10:12 AM
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

Tijl

03/30/2021, 10:19 AM
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

Hitender Pannu

03/30/2021, 10:20 AM
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

Tijl

03/30/2021, 10:21 AM
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

Hitender Pannu

03/30/2021, 10:28 AM
@Tijl correct, Even I use MutableStateFlow inside my Repo Impl, but interface will expose those variables as StateFlow
👌 1
w

wasyl

03/30/2021, 10:36 AM
You can also use actors
h

Hitender Pannu

03/30/2021, 10:37 AM
actors is something new to me, Sounds interesting do you have some reference I can checkout
j

Jilles van Gurp

03/30/2021, 10:52 AM
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

TheMrCodes

03/30/2021, 11:22 AM
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 👍
3 Views