List Adapter binds the old items before applying diffutil

43 views Asked by At

I was testing android listAdapter.

I update a single item in the list, then feed it to the List adapter.

I observe that first the view gets drawn using the old list, then the delta gets applied on top of the old list.

I am confused why the old list gets drawn? Shouldnt only the delta be bound if the old list is already bound to the UI. Why rebound the old list (i.e. the previous state) if it is already bound?

1

There are 1 answers

0
Cpp crusaders On

Fixed the issue.. error was as follows:

in my MainActivity I had:

override fun onCreate(savedInstanceState: Bundle?) {
 .....
 userViewModel.fetchAllUsers.observe(this,   Observer { it ->
        submitToAdapter(it)
    })
 ...
}
private fun submitToAdapter(
    usersList: List<UserEntity>
) {
   userAdapter.submitList(usersList)
   binding?.rvItemsList?.layoutManager = LinearLayoutManager(this)
   binding?.rvItemsList?.adapter = userAdapter
   binding?.rvItemsList?.visibility = View.VISIBLE
   binding?.tvNoRecordsAvailable?.visibility = View.GONE
}

The problem was the :

   binding?.rvItemsList?.layoutManager = LinearLayoutManager(this)
   binding?.rvItemsList?.adapter = userAdapter

This should be called exactly once in the OnCreate function and not each time we get result from the observer..

Fixed code:

override fun onCreate(savedInstanceState: Bundle?) {
 .....
 binding?.rvItemsList?.layoutManager = LinearLayoutManager(this)
 binding?.rvItemsList?.adapter = userAdapter
 userViewModel.fetchAllUsers.observe(this,   Observer { it ->
   submitToAdapter(it)
  })
 ...
}
private fun submitToAdapter(
    usersList: List<UserEntity>
) {
   userAdapter.submitList(usersList)
   binding?.rvItemsList?.visibility = View.VISIBLE
   binding?.tvNoRecordsAvailable?.visibility = View.GONE
}