ANDROID RECYCLERVIEW - DiffUtil and Data binding with RecyclerView 01

Dmitry Klokov·2020년 12월 27일
0

ANDROID-KOTLIN-FUNDAMENTALS

목록 보기
12/19
post-thumbnail

Review

The notifyDataSetChanged() method is inefficient

var data = listOf<SleepNight>()
	set(value) {
    		field = value
            	notifyDataSetChanged()
       }

However, notifyDataSetChanged() tells RecyclerView that the entire list is potentially invalid. As a result, RecyclerView rebinds and redraws every item in the list, including items that are not visible on screen. This is a lot of unnecessary work. For large or complex lists, this process could take long enough that the display flickers or stutters as the user scrolls through the list.

RecyclerView has a rich API for updating a single element. You could use notifyItemChanged() to tell RecyclerView that an item has changed, and you could use similar functions for items that are added, removed, or moved. You could do it all manually, but that task would be non-trivial and might involve quite a bit of code.

DiffUtil is efficient and does the hard work for me

RecyclerView has a class called DiffUtil which is for calculating the differences between two lists. DiffUtil takes an old list and a new list and figures out what's different. It finds items that were added, removed, or changed. Then it uses an algorithm called a Eugene W. Myers's difference algorithm to figure out the minimum number of changes to make from the old list to produce the new list.

Once DiffUtil figures out what has changed, RecyclerView can use that information to update only the items that were changed, added, removed, or moved, which is much more efficient than redoing the entire list.

Refresh list content with DiffUtil

profile
Power Weekend

0개의 댓글