【问题标题】:Android Repository pattern - how to update a nested recycler view item from view modelAndroid Repository 模式 - 如何从视图模型更新嵌套的回收器视图项
【发布时间】: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 时,我想更新数量;这里有两件事具有挑战性

  1. 我正在使用分页库中的 PagedListAdapter,它为我提供了一个(据说)不可变的产品列表。
  2. 即使我更新了 PagedList 并发出了 notifyDataSetChanged,仅仅更改大量项目的单个计数也太过分了。

我希望找到一种方法,可以轻松针对特定产品进行更新,或者我在网络上经常看到的另一种替代方法是构建自定义布局管理器,这样我就可以拥有一个单个适配器,可以一次绘制所有内容,而无需嵌套回收器视图。这样更新项目会变得更容易(找不到关于此的代码示例)。

请有任何建议。

【问题讨论】:

    标签: android mvvm repository-pattern android-viewmodel


    【解决方案1】:

    在 Paging3 中,计划最终添加一个 API 以支持粒度更新而不会失效:https://issuetracker.google.com/160232968

    目前,您必须使数据失效才能更新支持数据集。一般来说,DiffUtil 可以很好地向用户隐藏这一点。

    【讨论】:

    • 这就是我最终所做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 2012-02-28
    • 2021-07-01
    相关资源
    最近更新 更多