https://kotlinlang.org logo
#flow
Title
# flow
d

Daniel

02/12/2021, 12:49 PM
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

wasyl

02/12/2021, 12:50 PM
I typically use a
Mutex
and guard updates to the flow with it
d

Daniel

02/12/2021, 12:51 PM
My impression is that the loop I posted will be faster if in general there is no contention?
w

wasyl

02/12/2021, 1:04 PM
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

Daniel

02/12/2021, 1:05 PM
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
2 Views