The worst thing notifyDataSetChanged() do to your Android App performance

Hey, as a “Self taught” Android programmer you might have gone through tutorials and blogs about ListVews, Recyclerviews..etc

They use notifyDataSetChanged () for alerting adapters that there is some change data which have changed so that they can all fetch that new data and populate to their UIs.

It’s true that it notifies any registered observers that the data set has changed.

But I have been working on a pretty much large set of data processing lots of records for government facilities, and notifyDataSetChanged() has caused the App to stuck/ lag especially for the low spec smartphones.

The thing is, notifyDataSetChanged() forces all observers to assume the entire data set has been changed, but I was performing pagination that adds entries to existing ones).

This is why I decided to use DiffUtil .

DiffUtil calculates the new updates and just adds them to my current list and not refresh the whole list

void onNewDataArrived(List news) {
    List oldNews = myAdapter.getItems();
    DiffResult result = DiffUtil.calculateDiff(new MyCallback(oldEntry, newEntry));
    myAdapter.setNews(news);
    result.dispatchUpdatesTo(myAdapter);
}

What DiffUtil does in the above code is to compare what items does the new entry have which will be needed to add to OldEntry and it sets that result to the result variable

You will have to define a callback too which will be the one comparing the lists so you can make your logic there

Create a class and inherit DiffUtil.Callback()

This class will help you create set results

  • Whether two items have the same data.
  • Whether two objects represent the same Item.
  •  Know the size of the new list.
  • Knowing the size of the old list.
  • and much more

This has helped me to remove the lag that occurred. I hope you will want to try it out yourself, That’s it for now,

Thanks for reading, Let’s connect

Instagram : nickyrabit

Facebook : Nicholaus Legnard

Email : nicky@nickylegnard.com

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *