-
Notifications
You must be signed in to change notification settings - Fork 1.9k
What is the difference between setValue and update for MutableStateFlow? #3529
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Reading the value is atomic, setting the value is atomic, but reading and setting is not (two atomic operations don't make one atomic operation without any kind of external synchronization). The following race is possible:
That's where |
Thanks for taking time to answer. Separating read and write operations make me understood their difference now. I've changed the example to launch more than two coroutines; fun main() {
val loopCount = 100
val state = MutableStateFlow(0)
val numList = mutableListOf<Int>()
val diffList = mutableListOf<Int>()
runBlocking {
repeat(loopCount) {
launch(Dispatchers.Default) {
// Comment to test update function
val new = state.value + 1
state.value = new
println(new)
// Uncomment to test update function
// state.update {
// numList.add(it + 1)
// it + 1
// }
}
}
}
runBlocking {
for (num in 1..loopCount) {
if (numList.contains(num).not()) {
diffList.add(num)
}
}
println("numList: $numList")
println("numList size: " + numList.size)
println("missing number list: $diffList")
println("last value of state: " + state.value)
}
} Output example for setValue:
Output example for update
|
I was reading Michael Ferguson's Atomic Updates on MutableStateFlow post which was saying that there is a difference between
setValue
andupdate
. Then I checked documentation forvalue
and it was saying;And I thought If we don't need any external synchronization then we can use both
value
andupdate
for atomic operations. I've tried the post's example like below which was behaving same.Example:
Am I interpreting documentation wrong? Isn't it not needing any external synchronization = it's an atomic operation 🤔
The text was updated successfully, but these errors were encountered: