Alon Shlider
Alon Shlider

Reputation: 1298

notifyItemInserted renders the entire list again

I have the following method -

  private fun initRoomObserving() {
        dashboardViewModel = ViewModelProvider(this).get(DashboardViewModel::class.java)
        dashboardViewModel.getAllMessagesEntities().observe(this, Observer { receivedMessageList ->
            receivedMessageList.forEach {
                if (!userPhoneNumber.equals(it.senderUsername)) {
                    it.isReceiver = true
                }
                if (!messagesList.contains(it)) {
                    messagesList.add(it)
                }
            }
            conversationAdapter.notifyItemInserted(messagesList.size)
            conversationAdapter.notifyItemRangeChanged(messagesList.size - 1,messagesList.size)

        })
    }

For some reason the entire list is being rendered again for each time a new entity is beining added, even though I am explicitly notifyItemInserted and not notifyDataSetChanged

Why is this happening and what am I missing?

Upvotes: 1

Views: 59

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

The seconds parameter for notifyItemRangeChanged takes the count as value so since the value of changes item is always one so pass 1 instead of messagesList.size as:

conversationAdapter.notifyItemRangeChanged(messagesList.size - 1, 1)

Additionally, someCount can be variable which can track the number of changed items which can be used for notifyItemRangeChanged when you will have more then one item for updates.

Upvotes: 2

Related Questions