When I submit a new list to my ListAdapter, the RecyclerView is not refreshing with the updated data

Viewed 1502

I am developing a simple app, where people can add products to a basket (in the ProductsFragment) and then can change the quantity of the products in the basket (in the BasketFragment). I am using a RecyclerView with a ListAdapter for both fragments. I am using wrapping a LiveData instance around the Basket so I can observe any changes in the fragment. When I change the quantity the fragment is being notified and when this happens I am using the submitList() method of the ListAdapter to refresh only the changed data in the recyclerview. However, the DiffUtil areContentsTheSame() method is always returning true and so the RecyclerView items are not being updated until I go back to the previous fragment and back to the basket or I scroll the list.

ViewModel

private val _basket = MutableLiveData<Basket>()

val basket: LiveData<Basket>
    get() = _basket


fun onIncrementBasketProductQuantityButtonPressed(product: Product) {
    val newProduct = product.copy(quantity = product.quantity.plus(1))
    val newList= ArrayList(_basket.value!!.basket)

    val newBasket = _basket.value!!.copy(basket = newList)
    newBasket.updateProductInBasket(newProduct, newProduct.quantity)

    _basket.value = newBasket
}
Basket

data class Basket(@Json(name = "basket") val basket: MutableList<Product> = arrayListOf()): Serializable {

    fun updateProductInBasket(product: Product, quantity: Int) {
        val p = findProduct(product)

        if (p != null) {
            p.quantity = quantity
            p.setSubTotal()
        } else {
            addNewProductToBasket(product, quantity)
        }
    }

    private fun addNewProductToBasket(product: Product, quantity: Int) {
        product.quantity = quantity
        product.setSubTotal()

        this.basket.add(product)
    }

    private fun findProduct(product: Product) : Product? {
        return this.basket.find { it.name == product.name && it.size == product.size }
    }

}
0 Answers
Related