简体   繁体   English

如何通过两种不同方式(房间,用户)处理Android LiveData更改?

[英]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数据库的Android应用程序,该数据库使用REST API。 Room is acting as single source of truth, ie I am updating UI when API result is saved in the Room. Room充当单一事实来源,即,当API结果保存在Room中时,我正在更新UI。

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. 在我的一个屏幕中,我需要显示一个过滤列表(具有API的最新更新),例如,按作者过滤的电影列表。

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). 当用户更改作者过滤器时,需要更新列表,但是,由于API调用(存储在数据库中)而导致后端电影更改时,也需要更新列表。

Second I can achieve with LiveData> object that is created from Room call, it will dispatch changes from Room db. 其次,我可以使用通过Room调用创建的LiveData>对象来实现,它将从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. 对于其他任何人,使用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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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