我正在使用ViewModel和Repository模式来获取列表中的数据。项目排列为行和产品的列表。Row类中有产品。产品可以水平滚动。我使用具有线性布局管理器(水平方向)的RecyclerView嵌套在另一个RecyclerView(垂直方向)中。通过ViewModel获取项目并在RecyclerView中呈现非常简单。挑战在于当我尝试更新项目(它们的数量)时,当向购物车添加项目时。点击按钮(加号)后,通过侦听器将回调发送到ViewModel。水平适配器将请求发送回容器(垂直)适配器,而垂直适配器将其发送回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) {}
})
当结果为成功时,我想要更新数量;这里有两个挑战:
- 我正在使用来自分页库的PagedListAdapter,它给出了一个(据说是)不可变的产品列表。
- 即使我更新了PagedList并发出了notifyDataSetChanged,也会因为要在大量项目上更改单个计数而变得过于繁琐。
请提出任何建议。