What is the right way to atomically do What is the...
# flow
d
What is the right way to atomically do What is the right way to atomically do
mutableStateFlow.value += 1
? Is it
Copy code
var cached = mutableStateFlow.value
while (!mutableStateFlow.compareAndSet(cached, cached + 1)) {
    cached = mutableStateFlow.value
}
w
I typically use a
Mutex
and guard updates to the flow with it
d
My impression is that the loop I posted will be faster if in general there is no contention?
w
It might be 🙂 I haven’t thought about no-lock version like yours, personally I find it slightly less clear than a mutex but you’re right performance might be different. I haven’t profiled/checked though, I don’t know how much overhead it has
d
Thanks. In my case the race condition would be if a button file picker was opened and a file selected multiple times within a tiny window