android - 在 Android 中将多个 LiveData 对象聚合为一个 LiveData 聚合对象
问题描述
在我的 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 加载)。
解决方案
推荐阅读
- firebase - Firebase 验证规则。如何让规则发挥作用?
- php - 如何在 laravel 中与 API Guard 同步会话数据
- javascript - 如何使用 NodeJS/express JS 获取 MongoDB 中的文档数
- http - Flutter Dart - 如何使用 HttpClient() 发送 Post 请求
- xamarin - 如何在 xamarin 表单中单击时禁用 shell 弹出(菜单项)缩放
- php - 不加载模型的 Laravel OrderBy 关系计数(计数)
- python-3.x - Python Output Conversion
- android - 使用android更改html代码的值
- java - 当我尝试连接 ht2 数据库时,找不到数据库“mem:”,并且 IFEXISTS=true
- html - 我想要一个扩展表(左->右),但第一列是固定的