Ankit
05/28/2024, 8:06 AMMutableStateFlow.value
is thread-safe. The documentations does say so (documentation) but I see inconsistencies in the code below
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main():Unit = runBlocking {
val stateFlow = MutableStateFlow<Int>(0)
GlobalScope.launch {
for (i in 1..50000) {
stateFlow.value += 1
//stateFlow.update { curr -> curr + 1 }
}
}
GlobalScope.launch {
for (i in 1..50000) {
stateFlow.value += 1
//stateFlow.update { curr -> curr + 1 }
}
}
Thread.sleep(6000)
println(stateFlow.value)
}
The final value is not always 100,000. What am I missing? Can some one please help.Joffrey
05/28/2024, 8:07 AM+=
) is not an atomic operation: this operator will first read the value, then write an updated value. What happens in between is anyone's guess. This is what update
is for.Sam
05/28/2024, 8:09 AMSam
05/28/2024, 8:12 AMSam
05/28/2024, 8:13 AM