Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing MutableLiveData of list of items

I'm using LiveData and ViewModel from the architecture components in my app.

I have a list of items that is paginated, I load more as the user scrolls down. The result of the query is stored in a

MutableLiveData<List<SearchResult>> 

When I do the initial load and set the variable to a new list, it triggers a callback on the binding adapter that loads the data into the recyclerview.

However, when I load the 2nd page and I add the additional items to the list, the callback is not triggered. However, if I replace the list with a new list containing both the old and new items, the callback triggers.

Is it possible to have LiveData notify its observers when the backing list is updated, not only when the LiveData object is updated?

This does not work (ignoring the null checks):

val results = MutableLiveData<MutableList<SearchResult>>()  /* later */  results.value.addAll(newResults) 

This works:

val results = MutableLiveData<MutableList<SearchResult>>()  /* later */  val list = mutableListOf<SearchResult>() list.addAll(results.value) list.addAll(newResults) results.value = list 
like image 744
Francesc Avatar asked Mar 12 '18 23:03

Francesc


People also ask

How do I update my LiveData list?

Update LiveData objectsLiveData has no publicly available methods to update the stored data. The MutableLiveData class exposes the setValue(T) and postValue(T) methods publicly and you must use these if you need to edit the value stored in a LiveData object.

What is difference between live data and MutableLiveData?

By using LiveData we can only observe the data and cannot set the data. MutableLiveData is mutable and is a subclass of LiveData. In MutableLiveData we can observe and set the values using postValue() and setValue() methods (the former being thread-safe) so that we can dispatch values to any live or active observers.

What is a MutableLiveData?

MutableLiveData is just a class that extends the LiveData type class. MutableLiveData is commonly used since it provides the postValue() , setValue() methods publicly, something that LiveData class doesn't provide.

Is MutableLiveData thread-safe?

MutableLiveData is LiveData which is mutable & thread-safe. It's not really that LiveData is immutable, just that it can't be modified outside of the ViewModel class. The ViewModel class can modify it however it wants (e.g. a timer ViewModel).


1 Answers

I think the extension is a bit nicer.

operator fun <T> MutableLiveData<ArrayList<T>>.plusAssign(values: List<T>) {     val value = this.value ?: arrayListOf()     value.addAll(values)     this.value = value } 

Usage:

list += anotherList; 
like image 58
Samnang CHEA Avatar answered Sep 19 '22 11:09

Samnang CHEA