Hi All, I'm using StateFlow below is the code for ...
# android
d
Hi All, I'm using StateFlow below is the code for the same. I'm facing an issue where the update in the StateFlow data is not triggering the updation of value at one place and it is working fine at the other place.
Copy code
val commodityTopBarTitle = MutableStateFlow(HashMap<String,List<String>>())
val topBarTitleCommodity: StateFlow<HashMap<String,List<String>>> get() = commodityTopBarTitle
below is the method i use from UI to update the data in the StateFlow
Copy code
fun setCommodityTopBarTitle(key: String ,name: String) {
    if (commodityTopBarTitle.value.toMutableMap().containsKey(key)) {
        commodityTopBarTitle.value[key] =
            commodityTopBarTitle.value[key]!!.toMutableList().also {
                if (!it.contains(name)) {
                    it.add(name)
                } else {
                    it.remove(name)
                }
            }
    } else {
        val hashMap:HashMap<String,List<String>> = HashMap()
        val list = ArrayList<String>()
        list.add(name)
        hashMap[key] = list
        commodityTopBarTitle.value = hashMap
    }
}
At a different place in the UI i'm collecting it as state. To make sure any change in the data reflects on UI
Copy code
val titleData = questionnaireViewModel.topBarTitleCommodity.collectAsState()
but when the data is updated it does not show the new changes. In fact it feels like it is completely ignoring it. What is read about the StateFlow that the when ever there is the change in the data it automatically changes the value where ever it is being Observed. Is there something missing. Because i have been using the StateFlow at other places as well in the App but they are just of List types and they are working fine
e
That’s because you are making a local copy of the stateflow value, and editing that local value instead of actually setting the stateflow to a new map. Also, because of how stateflow works, mutable lists and maps will not update (someone can correct me as Im not 100% sure) because they are actually the same instance, even if you add elements to them and StateFlow only updates if the new value is different. So, use immutable data structures, and set the stateflow value to a new map every time you want it to update. OR use a SharedFlow with replay = 1 as it updates even if the value is the same.
🙏 1
271 Views