https://kotlinlang.org logo
Title
w

William Reed

07/09/2021, 12:30 PM
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
stateFlow.value = stateFlow.value.toMutableMap().apply { … modify …}
i could do this
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
stateFlow.mutate {
  ... modify ...
}
m

melatonina

07/09/2021, 1:29 PM
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

Nick Allen

07/12/2021, 5:35 AM
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.