We're taking a closer look into a new utility class from Android Support Library. It enables you to calculate the difference between two lists and output a list of update operations swiftly and with style. Presented by Željko Plesac from Infinum.
7. private List<E> items;
public void add(E item) {…}
public void addAll(Collection<E> collection) {…}
public void add(E item, int index) {…}
public void addAll(Collection<E> collection, int index) {…}
public void remove(E item) {…}
public void removeAll(Collection<E> collection) {…}
public void remove(int index) {…}
public void clear() {…}
10. We need to manually fetch the correct item from adapter and
update it’s content.
Need to handle edge cases - what happens if item is not
presented in adapter?
Blocks the UI thread.
PROBLEMS WITH UPDATE
12. Utility class that can calculate the difference between two lists
and output a list of update operations that converts the first
list into the second one.
DIFF UTIL
13. Uses Myers's difference algorithm to calculate the minimal
number of updates to convert one list into another.
Myers's algorithm does not handle items that are moved so
DiffUtil runs a second pass on the result to detect items that
were moved.
DIFF UTIL
14. If the lists are large, this operation may take significant time.
Use it on a background thread.
DIFF UTIL
15.
16. public class SportsBookDiffUtils extends DiffUtil.Callback {
…
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
Bundle bundle = new Bundle();
bundle.putInt(EXTRA_NUMBER_OF_EVENTS, newList.get(newItemPosition).getEventCount());
return bundle;
}
@Override
public int getOldListSize() {
return oldList != null ? oldList.size() : 0;
}
@Override
public int getNewListSize() {
return newList != null ? newList.size() : 0;
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return newList.get(newItemPosition).getSportId() == oldList.get(oldItemPosition).getSportId();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return newList.get(newItemPosition).getEventCount() ==
oldList.get(oldItemPosition).getEventCount();
}
}
20. It will block the UI (calculate the result on background thread
and, update on main).
Actual runtime of the algorithm significantly depends on the
number of changes in the list and the cost of your comparison
methods (more here).
Due to implementation constraints, the max size of the list can
be 2^26.
DRAWBACKS?
25. Provides a simple way to extend the default RecyclerView
behaviour with support for headers, footers, empty view,
DiffUtil and ArrayAdapter like methods.
Open sourced until Ragnarök.
MJOLNIR RECYCLERVIEW
26. Thank you!
Visit www.infinum.co or find us on social networks:
infinum.co infinumco infinumco infinum
@ZELJKOPLESAC
ZELJKO.PLESAC@INFINUM.CO