I am using live data to update some view of the activity. the view contain question numbers both total question number and answered question number eg: 2/10 (answered/total) the questions can be filtered using actors, if no actor is selected then it will list all questions (consider the total questions number as 100) then if I am selecting any actor(like a developer, HR) then the questions total number is reduced to another value something less than 100 (like 20 ) the total count is returned using the dao method
@Query("SELECT COUNT(actor) FROM questions WHERE actor IN (:actors)")
LiveData<Integer> getNumberOfQuestions(String[] actors);
here String[] actors is the selected actor list
Using an observer
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));
}
});
I am observing the count, but consider the scenario
onchanged in the first case returns 100 and in second it returns 100 and 20 I only want the current value, ie 20 how can solve this? what am I doing wrong?

in view model
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();
}
}
It's hard to know whole scenario but a few things in my mind about this
When you make new request with actor change, you doubling(and possibly more) live requests.
So as a result,
Before making new live request you can clear the previous one, or you can use List instead of LiveData.
Sample usage for clearing the observer of live query,
Hold the LiveData and Observer
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With