Hi, i have a question about updating state. in my app, our ViewModel holds the UiState which is a pl...
a
Hi, i have a question about updating state. in my app, our ViewModel holds the UiState which is a plain data class like this
Copy code
var mutableStateOf { UiState(etc) }
    private set
my question is, is updating this state via
Copy code
viewModelScope.launch {
    // is on main thread here
    uiState = uiState.copy(
            multiple params set here
        )
}
atomic, as long as its run on the main thread? found some guidance that suggests using
Snapshot.withMutableSnapshot
to make compose state updates atomic, but the example there is updating multiple
mutableStates
at once, not just one like in my example
f
What exactly do you mean by "atomic"?
a
i mean atomic in the sense that, if in another
viewModelScope.launch
i do a similar write to uiState, theres no risk of a race condition
as long as im not doing it on some random other thread eg with
withContext(IO)
or something
f
It's the same as with any other
var
in Kotlin. If you are running on the same thread, than atomicity should not be a problem I think
a
good to know! ive been having trouble fining reading material about the matter online in general
f
I think that when talking about
withMutableSnapshot
the "atomicity" means that all of the multiple changes of state inside that snapshot will be perceived by observers as one "atomic" change. It still wouldn't save you from race conditions If you are applying multiple snapshots to one variable.
But there are more clever people to talk about this in this channel so I'll stop there to not say anything wrong 😅
Maybe this thread might contain some relevant information
z
Any time you are doing a read + write it is not atomic. Another thread can change the value between when your thread does the read and the write. So for this case if you’re not synchronizing writes to that type some other way, you might want to use a snapshot.
That said, if you do have enough write contention to get into a situation where conflicting writes happen, you’re still going to have to specify how to handle them by supplying a merge policy, or the later snapshot will throw when you try to apply it. But an explicit exception is still better than sneaky inconsistent data.
a
my plan is to just keep these writes to the main thread, seems like there shouldn't be a problem this way