在我的 Android 应用程序中,我需要将 LiveData 对象列表聚合到这些对象的单个 LiveData 列表中,
简而言之:List<LiveData<T>> ====aggregate===> LiveData<List<T>>
.
我坚持使用MediatorLiveData
(参见下文)的方法,并想知道是否有任何开箱即用的解决方案或针对我的问题的既定模式。
领域模型
- 域类是
User
和Product
- 用户有一个最喜欢的产品列表,并且可以在他们的收藏夹中添加或删除产品
功能要求
- 作为一个活动,在列表中显示用户的收藏夹。用户可以从收藏活动的列表中删除产品。
- 有一个显示单个选定产品的活动。产品活动知道产品是否在给定用户的收藏夹中。在产品活动中,用户可以将产品添加到收藏夹或从收藏夹中删除产品
- 对收藏列表的更改必须反映在所有其他活动中,例如,如果用户在产品活动中将产品添加到收藏并导航到收藏活动,则该产品必须出现在收藏活动中
技术要求
- Java中的代码库
- 使用 Android 的 LiveData API 传播状态。RxJava 不是一个选项
我的方法
我设法编写了一个方法,该方法getFavoriteIds$(...)
返回一个LiveData<List<String>>
特定用户最喜欢的产品的 id,以及一个getProduct$(...)
从远程 API 获取单个产品的产品数据并返回一个LiveData<Product>
// returns a list of product ids
// that are in the favorites list of the user with the given userId
public LiveData<List<String>> getFavoriteIds$(final String userId) {
// implementation details skipped
}
// fetches product data for the given productId from a remote API
public LiveData<Product> getProduct$(final String productId) {
// implementation details skipped
}
我的目标是编写一个getFavorites$(...)
将用户 ID 作为输入并返回LiveData<List<Product>>
包含该用户产品完整列表的方法。
public LiveData<List<Product>> getFavorites$(final String userId) {
// Approach:
// First get ids of favorite products for the given user
// Transformations.switchMap(getFavoriteIds$(userId), ...)
// Then create
// MediatorLiveData<List<Product>> mediator$ = ...
// loop through the product ids of favorite products. For each productId
// product$ = getProduct$(productId)
// mediator$.addSource(product$, ...
// update mediator$.setValue(...) adding the value of product$ to the current array
// );
}
我的方法的问题在于它会mediator$
更新每个产品的值,但我只想更改一次,在所有产品都从远程 API 获取之后。挑战在于区分事件(用户添加了产品)和事件(产品数据已完成从远程 API 加载)。