NotifyDataSetChanged method does not refresh my RecyclerView Kotlin

Viewed 1256

I`m trying to understand why adapter method notifyDataSetChanged() not refresh my recyclerview. I find a solution when create method in adapter like this:

 fun setData(list: List<DownloadModel>){
    resumeList = list
    notifyDataSetChanged()
 }

This solution works but, i want to know why i can't do something like this:

private lateinit var downloadAdapter: DownloadRecyclerAdapter

private fun setupAdapter() {
    downloadAdapter = DownloadRecyclerAdapter(
        this@DownloadActivity,
        downloadList,
        { id -> onViewClick(id) },
        { id -> onEditClick(id) },
        { id, position -> onDeleteClick(id, position) }
    )

    savedResumeRv.apply {
        layoutManager = LinearLayoutManager(context)
        layoutAnimation = AnimationUtils.loadLayoutAnimation(
            this@DownloadActivity,
            R.anim.layout_animation_down_to_up
        )
        adapter = downloadAdapter

    }
}

private fun observers() {
    downloadViewModel.getDownloadList().observe(this, Observer { list ->
        downloadList = list
        list?.let {
            downloadAdapter.notifyDataSetChanged()
            }
        })
}

downloadAdapter hold same instance of list downloadList, and i wonder why when i notify adapter in activity not work properly.

2 Answers
 downloadList = list

because of this line it is not same reference to download list anymore

try

private fun observers() {
    downloadViewModel.getDownloadList().observe(this, Observer { list ->
      with(downloadList){
    clear()
    addAll(list)
}
        downloadList?.let {
            downloadAdapter.notifyDataSetChanged()
            }
        })
}

You have to do:

val resumeList: MutableList<DownloadModel>

 fun setData(list: List<DownloadModel>){
    resumeList.clear()
    resumeList.addAll(list)
    notifyDataSetChanged()
 }

I can agree that the previous reply will work for you, but it breaks the encapsulation of the data that the Adapter is holding. That is why in the first place you've hit that bug.

No client of the Adapter should be able to modify directly it's data without any protection.

Related