How to observe LiveData in RecyclerView adapter in MVVM architecture?

I know it's too late to answer. But I hope it will help other developers searching for a resolution on a similar issue.

Take a look at LiveAdapter.

You just need to add the latest dependency in Gradle.

dependencies {
    implementation 'com.github.RaviKoradiya:LiveAdapter:1.3.2-1608532016'
    // kapt 'com.android.databinding:compiler:GRADLE_PLUGIN_VERSION' // this line only for Kotlin projects
}

and bind adapter with your RecyclerView

LiveAdapter(
            data = liveListOfItems,
            lifecycleOwner = this@MainActivity,
            variable = BR.item )
            .map<Header, ItemHeaderBinding>(R.layout.item_header) {
                areContentsTheSame { old: Header, new: Header ->
                    return@areContentsTheSame old.text == new.text
                }
            }
            .map<Point, ItemPointBinding>(R.layout.item_point) {
                areContentsTheSame { old: Point, new: Point ->
                    return@areContentsTheSame old.id == new.id
                }
            }
            .into(recyclerview)

That's it. Not need to write extra code for adapter implementation, observe LiveData and notify the adapter.


After a full searching in several posts, finally, I found the recommended solution. Step 1: declare an interface in your adapter as below:

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)
            }
        }
    }
}

step 2: implement the interface in your view and pass it to your adapter like this:

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()
            }
        })
    }
}