我正在使用实时数据来更新活动的某些视图。该视图包含问题编号,包括总问题编号和已回答问题编号 例如:2/10(已回答/总计) 可以使用参与者过滤问题,如果未选择任何参与者,则它将列出所有问题(将问题总数视为100),然后如果我选择任何参与者(例如开发人员,HR),则问题总数将减少为另一个值小于100(例如20) 使用dao方法返回总计数
@Query("SELECT COUNT(actor) FROM questions WHERE actor IN (:actors)")
LiveData<Integer> getNumberOfQuestions(String[] actors);
此处String []演员是选定的演员列表
使用观察者
questionsViewModel.getTotalQuestionCount(mCheckedActorList).observe(this, new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer countTotal) {
if (countTotal != null)
mTotalCount = String.valueOf(countTotal);
if (mAnswerCount != null && mTotalCount != null)
mAllQuestionAnswered.setText(mAnswerCount.concat("/").concat(mTotalCount));
}
});
我正在观察数量,但是考虑一下情况
在第一种情况下不变,返回100,在第二种情况下,返回100和20 我只想要当前值,即20如何解决呢?我在做什么错了?
在视图模型中
public LiveData<Integer> getTotalQuestionCount(List<String> actorsList) {
if (actorsList != null && actorsList.size() > 0) {
String[] actorArray = new String[actorsList.size()];
actorArray = actorsList.toArray(actorArray);
return questionsRepository.getTotalCount(actorArray);
} else {
return questionsRepository.getTotalCount();
}
}
答案 0 :(得分:1)
很难了解整个场景,但我想知道一些有关此事
当您通过角色更改发出新请求时,您会将实时请求加倍(甚至更多)。
因此,
在发出新的实时请求之前,您可以清除上一个请求,或者可以使用列表代替LiveData。
用于清除实时查询的观察者的示例用法,
保留LiveData和观察者
Observer<Integer> observerOfLiveQuery = new Observer<Integer>() {
@Override
public void onChanged(@Nullable Integer countTotal) {
if (countTotal != null)
mTotalCount = String.valueOf(countTotal);
if (mAnswerCount != null && mTotalCount != null)
mAllQuestionAnswered.setText(mAnswerCount.concat("/").concat(mTotalCount));
}
}
LiveData<Intener> firstLiveQuery = getTotalQuestionCount(...)
firstLiveQuery.observe(this, observerOfLiveQuery)
LiveData<Intener> secondLiveQuery = getTotalQuestionCount(...)
firstLiveQuery.removeObserver(observerOfLiveQuery)
secondLiveQuery.observe(this, observerOfLiveQuery)