每次更新数据库中的值时,我都会观察到Activity中的更改。由于某种原因,更改被触发两次。一次使用旧值,一次使用新值。但是,它们不保留此顺序。就是说,有时候我首先获得旧价值,有时我首先获得新价值。
我在堆栈溢出时查找了问题,并遇到了启用持久性的问题。我也尝试过将“ Persistence Enabled”设置为false,但仍然没有运气:(。
// a view model for a data entity called topics
// the topicsHashMap is a Mutable Live data and being observed actively in the activity
//the hashmap is structured as follows: a community has multiple topics so hashmap has community id as key and arraylist of topics as items under the key in the hashmap
mTopicsViewModel.getTopicsHashMap().observe(mActivity, new Observer<HashMap<String, ArrayList<Topic>>>() {
@Override
public void onChanged(HashMap<String, ArrayList<Topic>> topicsHashMap) {
//getting the topics here
ArrayList<Topic> topics = topicsHashMap.get(mCommunityID);
//getting the current topics from the array list
Topic newTopic = topicsHashMap.get(mCommunityID).get(topics.indexOf(new Topic(mTopicID,null,null,null,0)));
//voting is an attribute of the topic object, I need to observe the voting changes in my activity. These changes are being returned twice.
//checking if current voting is not same as the new voting then change all ui
if(mCurrentVoting!=newTopic.voting){
mCurrentTopic = newTopic;
mCurrentVoting = mCurrentTopic.voting;
//voting alert dialog reflects all these changes in voting in real time
if(votingAlertDialog!=null){
if(votingAlertDialog.isShowing()) {
//then you need to update the views inside voting alert dialog as well
if (!userOption.name.isEmpty()) {
Logger.d("New voting added "+mCurrentVoting);
// calling the function that changes the ui accordingly
showVotingChangesOnAlertDialog();
}
}
}
}else{
Logger.d("Ignoring this voting change because its similar to previous");
}
}
});
对于每个数据库更改,仅预期对onDataChanged的一次调用; 但是,收到两个。