I have a `MutableStateFlow<Map<..., ...>&...
# coroutines
w
I have a
MutableStateFlow<Map<..., ...>>
what’s the most idiomatic way to mutate the map and update the
StateFlow
? seems like I need to make a copy of the current value and then update it? something like this seems verbose and awkward
Copy code
stateFlow.value = stateFlow.value.toMutableMap().apply { … modify …}
i could do this
Copy code
inline fun <K, V> MutableStateFlow<MutableMap<K, V>>.mutate(mutation: (MutableMap<K, V>) -> Unit) {
    val newValue = value.toMutableMap()
    mutation(newValue)
    value = newValue
}
and usage would just be
Copy code
stateFlow.mutate {
  ... modify ...
}
m
It's the same problem as replacing any observable collection with
StateFlow
, for example when using a
RecyclerView
on Android. Inexplicably, I never saw this addressed anywhere. I'm not an expert, though.
n
I suggest
MutableStateFlow<Map<K, V>>
. You can update it with just
stateFlow.value += item
or something similar. If you need more complicated mutations, then i think you are stuck with more complicated code.