Reputation: 800
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
Reputation: 40702
Actually, it's how you should update the adapter
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
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