Android Kotlin Best Approaches #1 — Chatting with ListAdapter and DiffUtil

Tolga Erbaş
2 min readJul 31, 2023

--

Chatting List Adapter with DiffUtil

In this article, I will teach how you can create ListAdapters with DiffUtil.

Sometimes we have a dynamic data comes from REST API, and we need to show this data in our views. Before the DiffUtil, notifyDataSetChanged() method refreshes the whole list even if the item in the list doesn’t have any change at all. So If you don’t want to refresh your whole list every time you add, remove or change an item in the list, you better use DiffUtil.

What is DiffUtil?

DiffUtil utility class that calculates the difference between two lists and outputs a list of update operations that converts the first list into the second one.

Lets create our project.

First, add viewBinding to your build.gradle file

buildFeatures{
viewBinding true
}

Then create your DiffUtil object like this.

List adapter is just an extension of RecyclerView.Adapter. Its computes differences between Lists on a background thread with AsyncListDiff.

I’m not going to explain 3 methods that are belong to the RecyclerView.Adapter.

Our ChatMessageSenderItem

Receiver item

And our receiver item.

We can create our ListAdapter like below

Then we are almost ready to use our ListAdapter using submitList() method in our fragment or activity.

   val listOfMessages = listOf<ChatMessage>(
ChatMessage(1, 1, "Hey, my name is Tolga", "21.07"),
ChatMessage(2, 2, "Nice to meet you Tolga", "21.08"),
ChatMessage(3, 2, "My name is Jessie", "21.08"),
ChatMessage(1, 1, "Nice to meet you Jessie", "21.09"),
)
binding.apply {
val chatAdapter = ChattingAdapter()
rvMessages.adapter = chatAdapter
chatAdapter.submitList(listOfMessages)
}

You can find full project in my github.

Until the next article, see ya!

For my previous articles

Feel free to contact me if you have any questions or suggestions.

--

--