fabi
fabi

Reputation: 474

How to change a live data instance in view model?

I am setting a room query in onCreate() which returns a live data instance that I observe in the following.

viewModel.setmQueryMediaList(null, MediaUtils.DATE_TAKEN_KEY, MediaUtils.DATE_TAKEN_KEY);

viewModel.getmQueryMediaList().observe(MainActivity.this, new Observer<List<MediaStoreData>>() {
        @Override
        public void onChanged(@Nullable List<MediaStoreData> mediaStoreDataList) {
            List<MediaStoreData> sectionedMediaStoreDataList = MediaUtils.getSectionedList(getBaseContext(), mediaStoreDataList, MediaUtils.ORDER_BY_MONTH );
            mRecyclerViewAdapter.submitList(sectionedMediaStoreDataList);
            Log.e("MediaDatabase", "something changed! Size:" + (mediaStoreDataList != null ? mediaStoreDataList.size() : 0));
        }
    });

onClick() I want to change the room query and I assumed that the observer triggers on that change but it doesn't.

@Override
public void onAlbumClicked(AlbumData albumData, TextView titleView) {
    viewModel.setmQueryMediaList(albumData.getDirectory_path(), null, MediaUtils.DATE_TAKEN_KEY);
    mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED);
}

This is in my ViewModel class

public void setmQueryMediaList(String directory_path, String sectionOrder, String sortOrder) {
    if(directory_path != null){
        this.mQueryMediaList = mediaDatabase.mediaDao().getAllByName();
    } else {
        this.mQueryMediaList = mediaDatabase.mediaDao().getAllByDate();
    }
}

public LiveData<List<MediaStoreData>> getmQueryMediaList(){
    return mQueryMediaList;
}

Any ideas what I am doing wrong?

Upvotes: 1

Views: 505

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81588

The correct way to do this would be to put the directoryPath in a MutableLiveData<String>, then do a Transformations.switchMap by it to update the LiveData that you're actually observing from your Activity/Fragment.

public void setmQueryMediaList(String directoryPath, String sectionOrder, String sortOrder) {
    directoryPathLiveData.setValue(directoryPath);
}

mQueryMediaList = Transformations.switchMap(directoryPathLiveData, (directoryPath) -> {
    if(directory_path != null){
        return mediaDatabase.mediaDao().getAllByName();
    } else {
        return mediaDatabase.mediaDao().getAllByDate();
    }
});

Upvotes: 1

glm9637
glm9637

Reputation: 894

Your problem is that you replace the Object which has the Observer attached. That means that you Obserers are not attached to your new QueryMediaList, so you would need to reset them every time you change the Query. To do that you could extract your Observer into its own variable, and then reatach that variable to the list, after you changed the query.

Upvotes: 1

Related Questions