Smart way to update RecyclerView using DiffUtil


Say Good Bye To notifyDataSetChanged()

We generally use List in any of our day to day development. It also requires to update the list data when user scrolls the list. To achieve this, we often fetch the data from server and update the newly received items.

If there is a small delay during this process it impact on the user experience so we want this to be done as soon as possible with along with less resources.

When the content of our list gets changed, we have to call notifyDataSetChanged() to get the updates but it is very costly. There are so many iterations for getting the job done in the case of notifyDataSetChanged().

Here DiffUtil class comes into picture and Android developed this utility class to handle data updates for a RecyclerView.


What is DiffUtil

As of 24.2.0, RecyclerView support library, v7 package offers really handy utility class called DiffUtil. This class finds the difference between two lists and provides the updated list as an output. This class is used to notify updates to a RecyclerView Adapter.

It uses Eugene W. Myers's difference algorithm to calculate the minimal number of updates.


How to use?

DiffUtil.Callback is an abstract class and used as callback class by DiffUtil while calculating the difference between two lists. It has four abstract methods and one non-abstract method. You have to extend it and override all its methods.

getOldListSize()– Return the size of the old list.

getNewListSize()– Return the size of the new list.

areItemsTheSame(int oldItemPosition, int newItemPosition)– It decides whether two objects are representing same items or not.

areContentsTheSame(int oldItemPosition, int newItemPosition)– It decides whether two items have same data or not. This method is called by DiffUtil only if areItemsTheSame returns true.

getChangePayload(int oldItemPosition, int newItemPosition)– If areItemTheSame returns true and areContentsTheSame returns false than DiffUtil utility calls this method to get a payload about the change.

Below are a simple Employee class which is using in the EmployeeRecyclerViewAdapter and EmployeeDiffCallback.

public class Employee {
    public int id;
    public String name;
    public String role;
}

Here is the implementation of Diff.Callback class. You can notice that getChangePayload() is not abstract method.

public class EmployeeDiffCallback extends DiffUtil.Callback {

    private final List<Employee> mOldEmployeeList;
    private final List<Employee> mNewEmployeeList;

    public EmployeeDiffCallback(List<Employee> oldEmployeeList, List<Employee> newEmployeeList) {
        this.mOldEmployeeList = oldEmployeeList;
        this.mNewEmployeeList = newEmployeeList;
    }

    @Override
    public int getOldListSize() {
        return mOldEmployeeList.size();
    }

    @Override
    public int getNewListSize() {
        return mNewEmployeeList.size();
    }

    @Override
    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
        return mOldEmployeeList.get(oldItemPosition).getId() == mNewEmployeeList.get(
                newItemPosition).getId();
    }

    @Override
    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
        final Employee oldEmployee = mOldEmployeeList.get(oldItemPosition);
        final Employee newEmployee = mNewEmployeeList.get(newItemPosition);

        return oldEmployee.getName().equals(newEmployee.getName());
    }

    @Nullable
    @Override
    public Object getChangePayload(int oldItemPosition, int newItemPosition) {
        // Implement method if you're going to use ItemAnimator
        return super.getChangePayload(oldItemPosition, newItemPosition);
    }
}

Once DiffUtil.Callback implementation are done, you have to update the list change in RecyclerViewAdapter as described below-

public class CustomRecyclerViewAdapter extends RecyclerView.Adapter<CustomRecyclerViewAdapter.ViewHolder> {
       public void updateEmployeeListItems(List<Employee> employees) {
        final EmployeeDiffCallback diffCallback = new EmployeeDiffCallback(this.mEmployees, employees);
        final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(diffCallback);

        this.mEmployees.clear();
        this.mEmployees.addAll(employees);
        diffResult.dispatchUpdatesTo(this);
    }
}

Call dispactUpdatesTo(RecyclerView.Adapter) to dispatch the updated list. DiffResult object that is returned from diff calculation, dispatches the changes to the Adapter, and adapter will be notified about the change.

Object returned in getChangePayload() is dispatched from DiffResult using notifyItemRangeChanged(position, count, payload), upon which is called Adapter’s onBindViewHolder(… List<Object> payloads) method.

@Override
public void onBindViewHolder(ProductViewHolder holder, int position, List<Object> payloads) {
 // Handle the payload
}


DiffUtil also uses methods of RecyclerView.Adapter to notify the Adapter to update the data set:

- notifyItemMoved()
- notifyItemRangeChanged()
- notifyItemRangeInserted()
- notifyItemRangeRemoved()

You can read more details on RecyclerView.Adapter and its method here.


Important: If the lists are large, this operation may take significant time so you are advised to run this on a background thread, get the DiffUtil.DiffResult then apply it on the RecyclerView on the main thread. Also max size of the list can be 2^26 due to implementation constraints.


Performance

DiffUtil requires O(N) space to find the minimal number of addition and removal operations between the two lists. It’s expected performance is O(N + D²) where N is the total number of added and removed items and D is the length of the edit script. You can walk through the official page of Android for more performance figures.

You can find the reference implementation of above example on GitHub.

To find more interesting topics on Software development follow me at Twitter GitHub




Comments

  1. Great blog.you put Good stuff.All the topics were explained briefly.so quickly understand for me.I am waiting for your next fantastic blog.Thanks for sharing.Any coures related details learn...

    Android Online Training

    ReplyDelete
  2. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    Regards,
    Android Course in Chennai|Android Training Chennai|best ios training in chennai

    ReplyDelete
  3. Thanks for sharing. Keep sharing

    ReplyDelete
  4. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.

    RPA Training in Bangalore

    ReplyDelete
  5. HawksCode is a leading company in Android app development who deliver the innovative solutions and engaging mobile apps. We have a team of professionals with years of experience which offer you futuristic and functional business apps for all Android devices. To take our services, drop your query at sales@hawkscode.com

    ReplyDelete
  6. This is great information and provide me some other idea out of the box. I would recommend for clean master and if you want more about this you can download app cache cleaner for android. I think it was very useful because it helped me clean out the junk in my mobile.

    ReplyDelete
  7. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.


    Hadoop Training in Chennai

    Aws Training in Chennai

    Selenium Training in Chennai

    ReplyDelete
  8. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    DevOps online Training|DevOps Training usa

    ReplyDelete
  9. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

    ReplyDelete
  10. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.

    python online training
    python training in chennai

    ReplyDelete
  11. A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.
    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  12. I am commenting to let you know what a terrific experience my daughter enjoyed reading through your web page
    safety course in chennai

    ReplyDelete
  13. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    AWS Interview Questions And Answers

    AWS Training in Chennai | Best AWS Training in Chennai

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    ReplyDelete
  14. Thanks for sharing this valuable information about Core Java with us, it is really helpful article!

    ReplyDelete
  15. Best Core Java Training Course in Delhi, Noida and Gurgaon. High Technologies Solutions is the best Core Java Training Institute in Delhi, Noida and Gurgaon providing Core Java Training classes by real-time faculty with course material and 24x7 Lab Facility.

    More info- Core Java Training Course in Delhi, Noida and Gurgaon

    ReplyDelete

  16. Information from this blog is very useful for me, am very happy to read this blog Kindly visit us @ Luxury Watch Box | Shoe Box Manufacturer |  Candle Packaging Boxes

    ReplyDelete
  17. Thank you for sharing such great information very useful to us.
    Fuse angular

    ReplyDelete
  18. Thanks for sharing this information. I really Like Very Much.
    online training institute

    ReplyDelete
  19. Amazing post, thanks for sharing this article. I am truly motivated by you for blogging.
    Thank You.
    One data science
    One Machine Learning

    ReplyDelete
  20. I definitely enjoying every little bit of it and I have you bookmarked to check out new stuff you post.
    One Machine Learning
    One data science
    Bissi.Global

    ReplyDelete
  21. I am really enjoying reading your well written articles . It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. keep it up the good work

    ReplyDelete
  22. Useful Information :

    Looking for the Best Digital Marketing Company in Vijayawada and Hyderabad affiliate agency in south INDIA, Digital Marketing in Vijayawada @ praiseads.com

    ReplyDelete
  23. Great Article

    Looking for the Best Walkin Interviews For Freshers , Find latest Govt Job Notifications with various information such as govt vacancies, eligibility, Bank Jobs, Latest Bank Job Updates @ pdtvjobs.com

    ReplyDelete
  24. Useful Information :

    Freshers Walkins provide information on all the job walkins happen in all over India. Popular IT Company jobs, Freshers walkins, java walkins, .net walkins @ http://fresherswalkins.co.in/

    ReplyDelete
  25. Useful Information :

    New Job Alert , New Job Alert Updates - Create New Job Alert notification alerts for bank jobs, government jobs, IT jobs, fresher new job alerts.

    ReplyDelete
  26. Nice Information

    Freshers Walkins provide information on all the job walkins happen in all over India. Popular IT Company jobs, Freshers walkins, java walkins, .net walkins @ http://fresherswalkins.co.in/

    ReplyDelete
  27. Useful Information :

    Are you planning to Study Abroad? Visit Study Abroad Institute one of the most trusted study abroad consultants in India and let overseas education in UK, USA @ http://studyabroadinstitute.com/

    ReplyDelete
  28. I always thinks for that work and always do that like seo & digital service .Digital MarketingThanks for sharing.

    ReplyDelete
  29. Useful Information :

    New Job Alert , New Job Alert Updates - Create New Job Alert notification alerts for bank jobs, government jobs, IT jobs, fresher new job alerts.

    ReplyDelete
  30. Useful Information :

    Looking for the Best Digital Marketing Company in Vijayawada and Hyderabad affiliate agency in south INDIA, Digital Marketing in Vijayawada @ praiseads.com

    ReplyDelete
  31. Useful Information :

    New Job Alert , New Job Alert Updates - Create New Job Alert notification alerts for bank jobs, government jobs, IT jobs, fresher new job alerts.

    ReplyDelete
  32. Great Article

    Looking for the Best Walkin Interview For Freshers , Find latest Govt Job Notifications with various information such as govt vacancies, eligibility, Bank Jobs, Latest Bank Job Updates @ pdtvjobs.com

    ReplyDelete
  33. Glad to be here, you have such a great thought. keep sharing more these types of article.

    ReplyDelete
  34. Two Way Radios and Accessories | Two Way Radio Rental, Repair, and Reprogramming | Cellphones and Tablets | Repeater Antenna Installs | Wireless Callboxes check out this page

    ReplyDelete

  35. One of the best articles ever, frankly, deserves to go into more and more depth. I had the pleasure of reading your article and I am proud of you for what you provide in your blog. You are an example of Arabic blogs that provide useful content.
    خبير سيو
    محترف سيو
    خدمات سيو
    خبير سيو
    تسويق عبر الفيديو
    محترف سيو
    خدمات سيو
    خبير سيو
    افضل شركة تصميم مواقع

    ReplyDelete
  36. I will provide various types of virtual services, so let us check out my professional & cheapest services at http://ow.ly/Y00I30qizKc and fulfill your needs.

    ReplyDelete
  37. Useful Information :

    Looking for Freshers Walkin interview and also Find Government Jobs Latest Bank Job Updates @ freshersworld.online

    ReplyDelete
  38. Hello Dear,

    We give you full opportunity to our website
    Our Admin About
    Our website Privacy-Policy

    Those of you who are interested in website design web development can visit our website and learn web design and development courses by watching our posts. Learn Web Design

    We must read this post to protect against coronavirus. coronavirus

    Thank you for read my comment.

    ReplyDelete
  39. Thanks for this post. It proves very informative for me. Great post to read. Keep blogging.

    If you are looking for the top security companies in London that provide its customer with remarkable security services. Check out this site for security services and private security companies

    ReplyDelete
  40. Thanks for this post. It proves very informative for me. Great post to read.

    If you are looking for the top security companies in London that provide its customer with remarkable security services. Check out this site for security services and private security guards

    ReplyDelete
  41. Thanks for this post. It proves very informative for me. Great post to read.Keep Blogging.

    Looking for Roller blinds, Wooden blinds, Cheap blinds, or Curtains and Venetian blinds, and more, in Nottingham and surrounding areas like Derby, Mansfield, Leciester, East Midlands or Luton? Day Blinds offers superior window solutions at unmatched prices.Visit our site for Pleated blinds Nottingham

    ReplyDelete
  42. I read the post it is a very good post . Its really nice post. I hope its useful to everyone . Phones

    ReplyDelete
  43. Thanks for this post. It proves very informative for me. Great post to read. Keep blogging.

    Looking for Roller blinds, Wooden blinds, Cheap blinds, or Curtains and Venetian blinds, and more, in Nottingham and surrounding areas like Derby, Mansfield, Leciester, East Midlands or Luton? Day Blinds offers superior window solutions at unmatched prices.Visit our site for Conservatory blinds Luton

    ReplyDelete
  44. Thanks for this post. It proves very informative for me. Great post to read. Keep blogging.

    If you are looking for the top security companies in London that provide its customer with remarkable security services. Check out this site for security services and rubbish removal london

    ReplyDelete
  45. It's really a nice and useful piece of information. I am satisfied that you shared this helpful info with us. Please stay us up to date like this. Thanks for sharing.

    If you are looking for the top security companies in London that provide its customer with remarkable security services. Check out our site for security services and Event & Club Security Specialists.We can help.

    ReplyDelete
  46. Looking for the ideal wireless car phone charger? Here is an exceptional pick that you can rely on for charging your phone devices. The unit is widely compatible, which makes it excellent for Samsung, iPhones, and more. Additionally, it has a suction cup base that offers better clamping on the windscreen. sinregeek is a famous wireless car charging brand, high quality and compatible price make it very popular in the market.

    https://www.wireless520.com/collections/wireless-car-charger


    It is also adjustable to provide better positioning of the charger for efficient charging. To add more, the unit has been built to serve longer and since it is phone case-friendly, you don’t have to detach the case when charging. It is a powerful 15W car charger that delivers a super-fast charging. It connects with all Qi-enabled devices for easy and quick charging. It has automatic clamping and opening clips that grip and close your phone when a phone is attached to a holder.

    ReplyDelete
  47. Worth reading! Our experts also have given detailed inputs about these trainings & courses! Presenting here for your reference. Do checkout
    oracle training in chennai & enjoy learning more about it.

    ReplyDelete
  48. Sharing the same interest, Infycle feels so happy to share our detailed information about all these courses with you all! Java Training in Chennai & get to know everything you want to about software trainings.

    ReplyDelete
  49. شركة تنظيف منازل بنجران يبحث الكثير عن شركات تنظيف موثوقة ومؤهلة للقيام بخدمات التنظيف بجودة عالية في التنفيذ،ولكن الان أصبح الأمر صعب لوجد الكثير من الشركات الغير موثوقة،كما انهم يقوموا بخدمات تنظيف سيئة مما يجعل العميل لا يثق في أي شركات تنظيف يكون لديها عمالة مصرية.
    ولكن عزيزي العميل قبل الاتصال بشركات التنظيف تأكد من ان الشركة موثوقة ومجربة وخدمتها متميزة،ونقدم اليوم لك أفضل شركة تنظيف منازل بنجران،حيث تتميز بأنها لديها خبرة اكثر من 9 سنوات في تنفيذ الأف الخدمات الممتازة،كما أنها تضم طاقم عمل مميز ولديه خبرة عالية وكفاءة وجودة في تقديم الخدمات بشكل ممتاز.
    شركة نقل اثاث بنجران

    شركة تنظيف خزانات بنجران

    شركة تسليك مجارى بنجران

    شركة شحن عفش من نجران لمصر

    شركة تنظيف منازل بيدمة

    شركة تنظيف منازل بنجران

    شركة تنظيف موكيت بنجران

    ReplyDelete
  50. Searching for the Oracle DBA Training in Chennai? Then come to Infycle for the best software training in Chennai. Infycle Technologies is one of the best software training institute in Chennai, which offers various programs in Oracle such as Oracle PLSQL, Oracle DBA, etc., in complete hands-on practical training from professionals in the field. Along with that, the interviews will be arranged for the candidates and 200% placement assurance will be given here. To have the words above in your life, call 7502633633 to Infycle Technologies and grab a free demo to know more.Top Oracle DBA Training in Chennai

    ReplyDelete
  51. There's so much information out there on the internet about the net that it is difficult to sift through the garbage to find solid info. I've been looking for ways to generate online income for over a year now and recently came across The CNRI Profit Machine. It's an EBook that has hundreds of pages of step-by-step instructions, testimonials, resources, etc that really hit the nail on the head. The concepts presented are extremely solid, and the author seems to understand the workings of internet marketing. You will not only learn how to earn real money online, but also how to do it while cutting out the "grueling" routine of work days and salary payments.
    Buy snapchat account

    ReplyDelete
  52. Finish the Big Data Certification in Chennai from Infycle Technologies, the best software training institute in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Java, Hadoop, Selenium, Android, and iOS Development, etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.Get Big Data Certification in Chennai | Infycle Technologies

    ReplyDelete
  53. Infycle Technologies, the top software training institute and placement center in Chennai offers the Best Digital Marketing course in Chennai for freshers, students, and tech professionals at the best offers. In addition to Digital Marketing, other in-demand courses such as DevOps, Data Science, Python, Selenium, Big Data, Java, Power BI, Oracle will also be trained with 100% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  54. Infycle Technologies, one of the topmost software training institutes in Chennai offers excellent Oracle PLSQL training in Chennai for freshers and students, and Tech Professionals of any field. Other demanding courses such as Digital Marketing, Java, Python, Hadoop, Selenium, Big Data, AWS, Android, and iOS Development will also be trained with complete hands-on training. After the completion of training, the students will be sent for placement interviews in the core MNC's. Dial 7504633633 to get more info and a free demo.Excellent Oracle PLSQL Training Chennai | Infycle Technologies

    ReplyDelete
  55. Now I found everything in this topic,thank you for sharing this.
    Selenium With C# Online Training
    Selenium with C#

    ReplyDelete
  56. Infycle Technologies, the No.1 software training institute in Chennai offers the No.1 Big Data Hadoop Training in Chennai | Infycle Technologies for students, freshers, and tech professionals. Infycle also offers other professional courses such as DevOps, Artificial Intelligence, Cyber Security, Python, Oracle, Java, Power BI, Selenium Testing, Digital Marketing, Data Science, etc., which will be trained with 200% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7502633633 to get more info and a free demo.

    ReplyDelete
  57. Awesome blog. Thanks for sharing this blog. Keep update like this...
    Android Training in Bangalore
    Android Classes in Pune

    ReplyDelete

Post a Comment

Popular posts from this blog

Android Performance: Avoid using ENUM on Android

Android O: Impact On Running Apps And Developer Viewpoint