1

Assume we have one data class called ProductCategory which contains the product category's name and a list of products for this category.

Product Category class:

data class ProductCategory(
    val id: String,
    val name: String,
    var products: List<Product>
)

Product class:

 data class Product(
        val id: String,
        val name: String,
        val productId: String,
        var isFavorite: Boolean = false,
    )

After calling an API to load the data and keep it on a Mutable State Flow object,

ViewModel class:

private var _productCategories = MutableStateFlow<List<ProductCategory>>(listOf())
val productCategories : StateFlow<List<ProductCategory>> = _productCategories.asStateFlow()

init {
        viewModelScope.launch {  
            repository.loadProducts()
                .flowOn(Dispatchers.IO)
                .collect { products ->
                    _productCategories.update { products }
                }
        }
    }

When user clicks the favorite button I need to update the field isFavorite. The problem is that if I try to update mutable state flow like this UI won't be notified for any change because the object that is being updated is the same with the current (we apply the change here on the same object)

_productCategories.update { 
        _productCategories.value.toMutableList().apply { 
                get(productCategoryIndex).products.apply { 
                    get(productIndex).isFavorite = true
                }
            }
        }

I tried to apply changes using a deep copied object and then update mutable state flow and it worked but it seems to be overkill... what can I do?

Lino
  • 5,084
  • 3
  • 21
  • 39
mpountou
  • 798
  • 8
  • 15

0 Answers0