I always forgot about DiffUtil. But it’s so beautiful!

Let’s take simple Recycler with Adapter and (in tradition) russian poets list.

Теперь пора заняться MainActivity:

We can run it – all works fine. But! Let’s add button handler:

Now, when we click Update button, list will changed. And ALL elements will be recreated an screen again. It can be confirmed, if we include logger in adapter  bind() method. And what if there are a lot of elements? And only one or two changed? This is where DiffUtil comes in handy. For begining, I will need a helper class that will do the magic:

As can be seen from the code, nothing complicated: it takes the old and the new lists, have two methods for return size of lists and two for comparison – by id (for example) and by content. The first comparing method is needed to determine if that elements is even. If their id is different, then there is no need to check further, this is definitely not the same object. But if the id is the same, then you can already connect the “big guns” – a method that compares the content, which is much more expensive in terms of resources, especially on large complex objects.

Now we can change handler code:

I will analyze in more detail. First, I create callback, by which comparisons will be made, I put both lists into it. Now, with  DiffUtil.calculateDiff()  help, compare lists. And call  RESULT.dispatchUpdatesTo(ADAPTER) , on comparsion result, who will do everything himself, and also with beautiful animation. Now we can run it.

CU, Code on GitHub.

Leave a Reply

Close Menu