如何在MVVM架构中观察RecyclerView适配器中的LiveData?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在MVVM架构中观察RecyclerView适配器中的LiveData?相关的知识,希望对你有一定的参考价值。

我有一个RecyclerView适配器和项目中的按钮。当我点击按钮时,我想从服务器中删除它的项目,然后从RecyclerView我想通过观察LiveData来做到这一点(当它从服务器中删除时我必须从回收站视图中删除它因此我需要服务器的结果)这样做的最佳实践方法是什么(我必须在片段中观察并将侦听器传递给适配器并在片段中实现它,当用户单击按钮时调用片段中的方法或者有更好的方法来实现)?

答案

经过几个帖子的全面搜索,最后,我找到了推荐的解决方案。第1步:在适配器中声明一个接口,如下所示:

class AddExpenseLabelAdapter(
    val items: List<LabelResponse>, 
    val context: Context, 
    val listener: OnLabelClickListener
) : RecyclerView.Adapter<AddExpenseLabelAdapter.ViewHolder>() {

    interface OnLabelClickListener {
        fun onLabelDeleteButtonClicked(request : SubCategoryLabelRequest)
    }

    lateinit var binding: ItemListExpenseAddLabelBinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(context)
        val binding = ItemListExpenseAddLabelBinding.inflate(inflater)
        this.binding = binding
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount(): Int = items.size

    inner class ViewHolder(val binding: ItemListExpenseAddLabelBinding) : RecyclerView.ViewHolder(binding.root), OnClickListener {
        lateinit var item: LabelResponse
        fun bind(item: LabelResponse) {
            this.item = item
            binding.itemListLabelLayout.setBackgroundColor(Color.parseColor("#" + item.color))
            binding.labelResponse = item
            binding.onClickListener = this
            binding.executePendingBindings()
        }

        override fun onClick(view: View) {
            if (view.id == binding.itemListLabelLayout.id) {
                val subCategoryLabelRequest = SubCategoryLabelRequest(item.id)
                listener.onLabelDeleteButtonClicked(subCategoryLabelRequest)
            }
        }
    }
}

第2步:在视图中实现接口并将其传递给适配器,如下所示:

class AddExpenseLabelDialog : DialogFragment(), AddExpenseLabelAdapter.OnLabelClickListener {

    lateinit var binding: DialogAddExpenseLabelBinding

    lateinit var view: Any

    var expenseId: Int = 0
    var categoryId: Int = 0

    lateinit var application: MyApplication

    lateinit var addExpenseLabelViewModel: AddExpenseLabelViewModel

    fun newInstance(expenseId: Int, categoryId: Int): AddExpenseLabelDialog = 
        AddExpenseLabelDialog().also { fragment ->
            arguments = Bundle().also { bundle ->
                bundle.putInt("expenseId", expenseId)
                bundle.putInt("categoryId", categoryId)
            }
        }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(layoutInflater, R.layout.dialog_add_expense_label, container, false)
        addExpenseLabelViewModel = ViewModelProviders.of(this).get(AddExpenseLabelViewModel::class.java)
        expenseId = arguments!!.getInt("expenseId")
        categoryId = arguments!!.getInt("categoryId")
        initialize()
        view = binding.root
        return view as View
    }

    fun initialize() {

        binding.labelRec.layoutManager = LinearLayoutManager(context)
        addExpenseLabelViewModel.liveData.observe(this, Observer { response ->
            binding.labelRec.adapter = AddExpenseLabelAdapter(response as ArrayList<LabelResponse>, context!!, this)
        })
    }

    override fun onLabelDeleteButtonClicked(request : SubCategoryLabelRequest) {
        addExpenseLabelViewModel.createExpenseLabel(categoryId, expenseId, request).observe(this, Observer { response ->
            when (response?.status) {
                Status.LOADING -> Toast.makeText(activity, "LOADING", Toast.LENGTH_SHORT).show()
                Status.SUCCESS -> {
                    dismiss()
                    Toast.makeText(activity, "SUCCESS", Toast.LENGTH_SHORT).show()
                }
                else -> Toast.makeText(activity, InjectorUtil.convertCodeToMessage(response?.error?.code!!), Toast.LENGTH_SHORT).show()
            }
        })
    }
}

以上是关于如何在MVVM架构中观察RecyclerView适配器中的LiveData?的主要内容,如果未能解决你的问题,请参考以下文章

MVVM中RecyclerView中的分页重复值

Android MVVM - 如何让 LiveData 发出它拥有的数据(强制触发观察者)

当notifyDataSetChanged与MVVM一起使用时,RecyclerView不会更新

如何在MVVM架构中使用RxSwift发送参数来查看模型?

在 MVVM 架构中格式化来自改造 API 的嵌套 JSON 响应 - Kotlin

recyclerView.addOnScrollListener - “使用 MVVM 改造分页”正在加载相同的响应/列表