Torben G
Torben G

Reputation: 800

Android - Add new Items to MutableLiveData and observe

How can I add new Items to a MutableLiveData List? I want to build an infinite scrolling Recyclerview. So I have a List with 10 items and after clicking a "load more button" I want to add ten new Items.

This are my lists of products:

private companion object {
        private var _products = MutableLiveData<MutableList<Product>>()
    }

    val products: LiveData<MutableList<Product>> = _products

Ant this is my loading function:

fun loadProducts(category: Category) { // category: String
        _isViewLoading.postValue(true)


        AppService.fetchProducts(category, neuheitenCounter) { success, response ->
            _isViewLoading.postValue(false)
            if(success) {
                when(category) {
                    Category.NEWS -> {
                        if(_products.value == null) {
                            _products.value = response?.products //as List<Product>
                        } else {
                            response?.let {
                                _products.value?.addAll(response?.products)
                            }
                        }

                        neuheitenCounter++
                    }
                }
            }
        }
    }

If I call _products.value = response?.products it fires the observe method in my Activity. But if I call addAll or add, the observer method is not called.

Upvotes: 5

Views: 11507

Answers (3)

DavidUps
DavidUps

Reputation: 420

MutableLiveData.postValue(T value)

Upvotes: 1

Valeriy Katkov
Valeriy Katkov

Reputation: 40702

Actually, it's how you should update the adapter

  1. Add new items to the existing list
  2. Notify LiveData by assigning the same list to its value. Here is the same question with the solution.
  3. When your Activity is notified that the list is changed, it should notify the adapter about the changes by calling its notifyDataSetChanged() method.

When you call notifyDataSetChanged() method of the adapter, it compares previous items with the new ones, figures out which of them are changed and updates the RecyclerView. You can help the adapter by calling notifyItemRangeInserted() instead of notifyDataSetChanged(). notifyItemRangeInserted() accepts a range on inserted items, in your case you can calculate it but taking the difference between adapter.itemCount and the productList.size.

Upvotes: 4

Rahul sharma
Rahul sharma

Reputation: 1574

I had that same issue .I copied data of LiveData in new List then i added new data to new List.And assigned new List to LiveData.I know this not exact SOLUTION but this solved problem.

Try this.

    var tempList= _products.value
    tempList.addAll(response?.products)
    _products.value = tempList

I hope this will help you.

Upvotes: 0

Related Questions