0

I am displaying markers from my database on my map, But i have a filter for the user from where he can adjust the time and the markers will show in that time. I want to observe the list that is updated each time when the user changes the time filter. He selects a start time and end time and I query from the database to get a list with that condition .. I want to observe this list? How can I do that?

my ViewModel:

      public MediatorLiveData<List<LocationTracking>> fetchData(LiveData<List<LocationTracking>> source){
    if (oldSource == null){
        oldSource = source;
    } else {
        list.removeSource(oldSource);
    }
    list.addSource(source, locationTrackings -> {
        list.postValue(locationTrackings);
    });
    return list;
}

And in my activity I'm doing this:

My callback isn't called for on change when a new value is inserted in my database. Any help would be highly appreciated.

When the user wants to see whole list without time filter.

mViewModel.fetchData(mViewModel.getFilteredLocationList(
                        mDataRange.get(0).getTimeStamp(),
                        mDataRange.get(1).getTimeStamp()
                )).observe(this,mFilteredListObserver);

When the user selects a time Filter.

mViewModel.fetchData(mViewModel.getFilteredLocationList(
                data.getLongExtra(LocationsFilterActivity.START_TIME, 0),
                data.getLongExtra(LocationsFilterActivity.END_TIME, 0)
        )).observe(this,mFilteredListObserver);

1 Answers1

0

I've struggled with a similar problem. Once you understand the solution it's quite simple. You need to do something like this in your ViewModel:

private MutableLiveData<DataRange> dataRange = new MutableLiveData<DataRange>();
public LiveData<List<LocationTracking>> list = Transformations.switchMap(dataRange, 
newDataRangeValue -> getFilteredLocationList(
        newDataRangeValue.get(0).getTimeStamp(),
        newDataRangeValue.get(1).getTimeStamp())
);

public void onDataRangeChanged(DataRange dataRange) {
    this.dataRange.setValue(dataRange);
}

In your Activity observe the list. The switchMap() method will listen for any changes on dataRange so if you do mViewModel.onDataRangeChanged(newDataRange), getFilteredLocationList() will be called again and list will be updated in Activity.

I highly recommend reading this great article.

Wess
  • 779
  • 8
  • 12