问题
I found that the LiveData returned by Dao will call its observer whenever the row is updated in DB, even if the LiveData value is obviously not changed.
Consider a situation like the following example :
Example entity
@Entity
public class User {
public long id;
public String name;
// example for other variables
public Date lastActiveDateTime;
}
Example Dao
@Dao
public interface UserDao {
// I am only interested in the user name
@Query("SELECT name From User")
LiveData<List<String>> getAllNamesOfUser();
@Update(onConflict = OnConflictStrategy.REPLACE)
void updateUser(User user);
}
Somewhere in background thread
UserDao userDao = //.... getting the dao
User user = // obtain from dao....
user.lastActiveDateTime = new Date(); // no change to user.name
userDao.updateUser(user);
Somewhere in UI
// omitted ViewModel for simplicity
userDao.getAllNamesOfUser().observe(this, new Observer<List<String>> {
@Override
public void onChanged(@Nullable List<String> userNames) {
// this will be called whenever the background thread called updateUser.
// If user.name is not changed, it will be called with userNames
// with the same value again and again when lastActiveDateTime changed.
}
});
In this example, the ui is only interested to user name so the query for LiveData only includes the name field. However the observer.onChanged will still be called on Dao Update even only other fields are updated. (In fact, if I do not make any change to User entity and call UserDao.updateUser, the observer.onChanged will still be called)
Is this the designed behaviour of Dao LiveData in Room? Is there any chance I can work around this, so that the observer will only be called when the selected field is updated?
Edit : I changed to use the following query to update the lastActiveDateTime value as KuLdip PaTel in comment suggest. The observer of LiveData of user name is still called.
@Query("UPDATE User set lastActiveDateTime = :lastActiveDateTime where id = :id")
void updateLastActiveDateTime(Date lastActiveDateTime, int id);
回答1:
This situation is known as false positive notification of observer. Please check point number 7 mentioned in the link to avoid such issue.
Below example is written in kotlin but you can use its java version to get it work.
fun <T> LiveData<T>.getDistinct(): LiveData<T> {
val distinctLiveData = MediatorLiveData<T>()
distinctLiveData.addSource(this, object : Observer<T> {
private var initialized = false
private var lastObj: T? = null
override fun onChanged(obj: T?) {
if (!initialized) {
initialized = true
lastObj = obj
distinctLiveData.postValue(lastObj)
} else if ((obj == null && lastObj != null)
|| obj != lastObj) {
lastObj = obj
distinctLiveData.postValue(lastObj)
}
}
})
return distinctLiveData
}
回答2:
There is simple solution in Transformations method distinctUntilChanged
.expose new data only if data was changed.
In this case we get data only when it changes in source:
LiveData<YourType> getData(){
return Transformations.distinctUntilChanged(LiveData<YourType> source));
}
But for Event cases is better to use this: https://stackoverflow.com/a/55212795/9381524
回答3:
Currently there is no way to stop triggering Observer.onChanged which is why I think the LiveData will be useless for most of the queries that are using some joins. Like @Pinakin mentioned there is a MediatorLiveData but this is just a filter and the data still gets loaded on every change. Imagine having 3 left joins in 1 query where you only need a field or two from those joins. In case you implement PagedList every time any record from those 4 tables (main + 3 joined tables) gets updated, the query will be called again. This is OK for some some tables with small amount of data, but correct me if I wrong this would be bad in case of bigger tables. It would be best if we would have some way of setting the query to be refreshed only if the main table is updated or ideally to have a way to refresh only if fields from that query are updated in the database.
回答4:
I stuck with the same problem.
What i did wrong:
1) creating anonimous object:
private LiveData<List<WordsTableEntity>> listLiveData;
// listLiveData = ... //init our LiveData...
listLiveData.observe(this, new Observer<List<WordsTableEntity>>() {
@Override
public void onChanged(@Nullable List<WordsTableEntity> wordsTableEntities) {
}
});
In my case, I called the method several times in which this line was located.
From the docs i supposed, that new Observers take data from LiveData. Because of that, author could receive few onChanged
methods from few new anonimous Observers, if he set observe userDao.getAllNamesOfUser().observe(this, new Observer
that way.
Its will be better to create named Observer object before LiveData.observe(...
and once
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
observer = new Observer<List<WordsTableEntity>>() {
@Override
public void onChanged(@Nullable List<WordsTableEntity> wordsTableEntities) {
adapter.setWordsTableEntities(wordsTableEntities);
progressBar.setVisibility(View.GONE);
}
};
}
and then set it LiveData.observe(observer
and we receive data from LieData first time and then, when data will be changed.
2) Observing one Observe object multiple times
public void callMethodMultipleTimes(String searchText) {
listLiveData = App.getRepositoryRoomDB().searchDataExceptChapter(searchText);
listLiveData.observe(this, observer);
}
I calling this method multiple times and debug showed me, that i was adding my observer
as many times, as i called callMethodMultipleTimes();
Our listLiveData
is a global variable and it lives. It changes the object reference here
listLiveData = App.getRepositoryRoomDB().searchDataExceptChapter(searchText);
, but the old object in memory is not immediately deleted
This will be fixed, if we call listLiveData.removeObserver(observer);
before
listLiveData = App.getRepositoryRoomDB().searchDataExceptChapter(searchText);
And returning to 1) - we can not call listLiveData.removeObserver(our anonimous Observer);
because we do not have an anonymous object reference.
So, in the result we can do so:
private Observer observer;
private LiveData<List<WordsTableEntity>> listLiveData;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
observer = new Observer<List<WordsTableEntity>>() {
@Override
public void onChanged(@Nullable List<WordsTableEntity> wordsTableEntities) {
adapter.setWordsTableEntities(wordsTableEntities);
progressBar.setVisibility(View.GONE);
}
};
}
public void searchText(String searchText) {
if (listLiveData != null){
listLiveData.removeObservers(this);
}
listLiveData = App.getRepositoryRoomDB().searchDataExceptChapter(searchText);
listLiveData.observe(this, observer);
}
I didn't use distinct functions. In my case it works without distinct.
I hope my case will help someone.
P.S. Version of libraries
// Room components
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
androidTestImplementation "android.arch.persistence.room:testing:1.1.1"
// Lifecycle components
implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
来源:https://stackoverflow.com/questions/47215666/room-livedata-from-dao-will-trigger-observer-onchanged-on-every-update-even-i