Stop Using RecyclerView.Adapter
Migrate to ListAdapter for your RecyclerView in 3 simple steps.
There are only 3 easy steps to migrate your RecyclerView.Adapter
class to a ListAdapter
.
Why and when should I migrate?
When you have a recycler view that requires constantly changing over time, you need to use a ListAdapter. By default, the RecyclerView implementation of changing the list items is inefficient. As developers, we need to look for efficient solutions.
What is DiffUtil?
Google came up with a class called DiffUtil
that compares the currently existing list with the newly submitted list; it changes the necessary UI on the screen only. However, this was adding to the already elaborate boilerplate code and hence, we can use a ListAdapter
for reducing the boilerplate.
#0 — Getting Started
This is your traditional RecyclerView Adapter that you see here. We shall modify this class to use ListAdapter
instead.
#1 — Create the DiffUtil Callback
As stated earlier, we need to use the DiffUtil so that we compare the lists efficiently.
We can start by creating a static anonymous object of the interface. We have two functions here:
areItemsTheSame
— This function returns true if the items that we are comparing are the same. We usually do this by comparing the Primary Key of the modals.areContentsTheSame
— This function returns true if the other properties of the items are the same. This checks whether there are any internal changes within the item itself.
#2 — Replace the Inherited Class
Now we can replace the RecyclerView.Adapter
to the ListAdapter
.
We pass the object of the DiffUtil
in the parent constructor. We have successfully migrated our class to a ListAdapter
; however, our code is still not what we need yet.
#3 — Adding the final touches.
Now that you are using ListAdapter
, it makes sense to leverage the power we get from it.
- You can remove the
getItemCount
function.ListAdapter
implements that for you. - Replace the
list
property as shown below. - Change
list[position]
togetItem(position)
.
Conclusion
With a few minor changes, and following these 3 simple steps, you can improve the performance of your application significantly. ListAdapter
uses the RecyclerView.Adapter
inherently and made it better performant. If your list varies continuously, then using a ListAdapter
is always a good preference.