4

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 }
    }

}
Pritam Sangani
  • 271
  • 1
  • 15
  • 1
    Call `adapter.notifyDataSetChanged()` after the data has changed – HB. Jun 28 '19 at 16:40
  • 2
    I don't want to use notifyDataSetChanged() as that blocks the UI thread and refreshes the whole list so no animation. I want to use submitList() but I am having problems with the ListAdapter getting the new LiveData before submitList(), so it doesn't know which item has changed. – Pritam Sangani Jun 28 '19 at 16:42
  • Then have a look at this question - https://stackoverflow.com/q/49726385/5550161 – HB. Jun 28 '19 at 16:46
  • You know you can also use `adapter.notifyItemChanged(position)`, this will only update the specific item. – HB. Jun 28 '19 at 16:50
  • Having the same problem but using LiveData. When I add directly it works. – TheRealChx101 Sep 17 '19 at 15:42
  • @TheRealChx101 hey what do you mean by add it directly? – Guy Nov 01 '19 at 18:17
  • @Guy. I don't even remember what the issue was. I had long fixed it. Sorry. – TheRealChx101 Nov 01 '19 at 21:54

0 Answers0