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

Lukas Lechner

08/10/2022, 12:43 PM
Why does the
.value
property in the MutableStateFlow documentation say that it is thread-safe, when it clearly isn't (when e.g. concurrently increasing an integer value from multiple concurrent coroutines)
s

Sam

08/10/2022, 12:51 PM
By “thread safe” here they just mean that it won’t break when multiple threads use it at the same time.
Incrementing a value really takes two operations; a read and then a write. “Thread-safe” just means that multiple threads can read and write the value concurrently. It doesn’t necessarily guarantee anything about the order that those reads and writes happen in.
If you need atomic increments there is MutableStateFlow.update 👍
l

Lukas Lechner

08/10/2022, 1:33 PM
Thanks @Sam
s

statmark56

09/10/2022, 6:55 AM
Ngl, the last part
without external synchronization
does sound convincing though that it is thread-safe in general term 🙈
2 Views