Hey I think thats not the right approach: I want t...
# compose
j
Hey I think thats not the right approach: I want to have a map where the key is the "shop" and the value is a list of products. I currently use this for the map and this function for adding a value:
Copy code
private val products: SnapshotStateMap<String, List<ShoppingItem>> = mutableStateMapOf()

fun add(shop: String, product: ShoppingItem) {
    val list = products.getOrDefault(shop, mutableListOf()).toMutableList()
    list.add(product)
    products[shop] = list
}

fun replace(shop: String, product: ShoppingItem) {
    val list = products.getOrDefault(shop, mutableListOf()).toMutableList()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        list.replaceAll { if (it.id == product.id) product else it }
    }
    products[shop] = list
}
I mean adding works but the replace method doesn't wanna work and I don't think thats the right way
h
Don’t put a mutable collection (or any mutable class) inside a
State
. Instead adding a new product the inner list, you should update the entry of
products
with a readonly list
j
Like that?
Copy code
products[shop] = list.toList()
or like that?
Copy code
products[shop] = products.getOrDefault(shop, listOf()).plus(product)
h
Last one is a shortcut, and I would prefer it 🤷‍♂️
j
lemme try it
replace won't work as I said adding always worked
any idea for this?
h
Do you have a reproducer?
j
Not really, I click a button call my API and update the ui with the replace method
Nvm I'm dumb