【发布时间】:2020-07-27 14:00:26
【问题描述】:
我正在使用 ViewModel 和存储库模式来获取列表中的数据。这些项目被排列为行和产品的列表。 Row 类中有产品。产品可以水平滚动。我正在使用一个带有线性布局管理器(水平方向)的回收器视图,它嵌套在另一个回收器视图(垂直方向)中。通过 ViewModel 获取项目并在回收器视图中呈现非常简单。挑战是当我尝试在将商品添加到购物车时更新商品(它们的数量)。单击按钮(加号)时,会通过侦听器将回调发送到视图模型。水平适配器将请求发送回容器(垂直)适配器,垂直适配器将请求发送回视图模型。
// The horizontal adapter
class SimpleProductAdapter(
private val shopId: String,
private val listener: (product: CartProduct) -> Unit
) :
ListAdapter<CartProduct, RecyclerView.ViewHolder>(...DiffCallbackGoesHere) {
// ... some more things here
fun bind(item: CartProduct?) {
view.add_to_cart_button.setOnClickListener {
listener(item)
}
}
垂直适配器结构类似
class RowAdapter(
private val shopId: String,
private val listener: (product: CartProduct) -> Unit
) :
PagedListAdapter<Row, RecyclerView.ViewHolder>(...RowDiffCallbackGoesHere) {
// ... some more things here
fun bind(item: Row?) {
SimpleProductAdapter(shopId) { product ->
listener(product)
}
}
以及存在视图模型调用的片段内的主要站点:
val rowAdapter = RowAdapter(args.shopId) { product->
if (actionType == ADD_TO_CART_ACTION) viewModel.buy(product)
.observe(viewLifecycleOwner, Observer {
view.swipe.isRefreshing = it is Resource.Loading
// I want to update the quantity here on success result
if(Resource is Success) {}
})
当结果为 Success 时,我想更新数量;这里有两件事具有挑战性
- 我正在使用分页库中的 PagedListAdapter,它为我提供了一个(据说)不可变的产品列表。
- 即使我更新了 PagedList 并发出了 notifyDataSetChanged,仅仅更改大量项目的单个计数也太过分了。
我希望找到一种方法,可以轻松针对特定产品进行更新,或者我在网络上经常看到的另一种替代方法是构建自定义布局管理器,这样我就可以拥有一个单个适配器,可以一次绘制所有内容,而无需嵌套回收器视图。这样更新项目会变得更容易(找不到关于此的代码示例)。
请有任何建议。
【问题讨论】:
标签: android mvvm repository-pattern android-viewmodel