我是房间和实时数据的新手。我的任务是通过服务获取数据并将其插入会议室数据库中,并通过livedata观察器更新UI,但是每当我执行此任务时,由于livedata的更改(插入,更新或删除),观察器都会调用3次。但是实际上我需要的是在完成所有查询(插入/更新/删除)之后仅调用一次观察者,然后从主线程中删除观察者。请任何人帮助解决
主片段中的观察者初始化:
int updateCount=0; // i don't like to use this count
public void configureViewModel(){
SCREEN_ID=SCREEN_NO_ADDRESS_DETAIL;
viewModel = ViewModelProviders.of(this, viewModelFactory).get(DynamicUIViewModel.class);
viewModel.init(SCREEN_ID,loanType);
Observer observer=new Observer() {
@Override
public void onChanged(@Nullable Object o) {
List<DynamicUITable> list=(List<DynamicUITable>)o;
updateCount++;
if(updateCount==3) {
viewModel.getDynamicUITableLiveData().removeObserver(this); // i want to remove observer without checking this updateCount condition.
updateCount=0;
updateUI(list);
}
}
};
viewModel.getDynamicUITableLiveData().observe(getViewLifecycleOwner(), observer);
}
Repository Class :
public LiveData<List<DynamicUITable>> init(String screenName,String loanType){
try {
refreshData(screenName,loanType);
}catch (Exception ex){
ex.printStackTrace();
}
return dynamicUIDao.load(screenName);
}
Service call method :
private void refreshData(final String screenName,String loanType){
try{
executor.execute(()->{
boolean dataExist = (dynamicUIDao.getTableBasedOnScreen(screenName) != null);
dynamicUIWebservice.getDynamicUIFromServer(screenName).enqueue(new Callback<List<DynamicUITable>>() {
@Override
public void onResponse(Call<List<DynamicUITable>> call, Response<List<DynamicUITable>> response) {
Log.e("TAG", "DATA REFRESHED FROM NETWORK");
executor.execute(()-> {
List<DynamicUITable> dynamicUITableList = response.body();
if (dynamicUITableList != null) {
if (dataExist) {
dynamicUIDao.deleteRecords(screenName);
dynamicUIDao.save(dynamicUITableList);
} else {
dynamicUIDao.save(dynamicUITableList);
dynamicUIDao.load(screenName);
}
/* From here observer is calling whenever live data changes but what i need is , i need to
call observer only one time after completion all query operation*/
}
});
}
@Override
public void onFailure(Call<List<DynamicUITable>> call, Throwable t) {
}
});
});
}catch (Exception ex){
ex.printStackTrace();
}
}