I select Information from DB using LiveData, passing it to my Activity (via DAO, Repository & Viewmodel) dependent from a timespan of Dates. When I change the timespan, I want to remove the old Observers on the LiveData and create new Observer for the new Timespan.
private void addStepsObserver(Date[] timeSpan) {
homeViewModel.getSteps(timeSpan[0], timeSpan[1]).observe(this, new Observer<Integer>() {
@Override
public void onChanged(Integer integer) {
if (integer == null) {
return;
}
Log.i(StepRepository.TAG, "onChanged for getSteps().observe called " + integer);
updateStepCounter(integer);
}
});
}
private void removeObservers() {
Date[] timeSpan = homeViewModel.getCurrentTimespan();
homeViewModel.getSteps(timeSpan[0], timeSpan[1]).removeObservers(this);
Log.i(TAG, "remove Observers " + timeSpan[0] + " " + timeSpan[1]);
}
However, after I call removeObservers()
and then addStepsObservers(timespan)
with timespan being another timestamp than before, the method updateStepCounter()
is called by both observers, although the old one isn't active anymore (I checked that using .hasObservers()
and .hasActiveObservers()
)
Any advices?
homeViewModel.getSteps()
- returns a new LiveData
for each call? So, it means that you remove an observer from another newly created LiveData
. You have to keep a reference to LiveData
object created in addStepsObserver
step and in removeObservers
step you should remove observers from it.