简体   繁体   中英

How to handle Android LiveData changes from two different ways (Room, user)?

I have an Android app with a Room database which consumes REST API. Room is acting as single source of truth, ie I am updating UI when API result is saved in the Room.

In one of my screens, I need to show a filtered list (with the latest updates from API), for example, List of movies filtered by author.

When the user changes author filter, the list needs to be updated, but also, the list needs to be updated when movies change in the backend as a result of an API call (stored in the db).

Second I can achieve with LiveData> object that is created from Room call, it will dispatch changes from Room db.

But, how do I incorporate changes activated from user (by switching filter) over same source (filtered list of movies)?

For anyone else, it's actually quite simple with MediatorLiveData.

val selectedItem = MediatorLiveData<Voyage>() 

var voyages: LiveData<Resource<List<Voyage>>>

var voyageFilter = MutableLiveData<VoyageFilter>()

selectedItem.addSource(voyageFilter) { filter -> 
//do something   
 }

selectedItem.addSource(voyages) { listResource ->
        //do something

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM