First arrival of new data for your empty
RecyclerView.Adapter is trivial, just consume the event and you are all set. I’ve spent a lot of time finding less hassle ways to trigger updates when new data arrives when my adapter is not empty. I had to look for ranges and indices and what not, many iterations for nothing.
As of 24.2.0, RecyclerView support library, v7 package offers really handy class called SortedList. It’s a life saver. It was implemented to bound to a RecyclerView, it is not a type of
java.util.List, it doesn’t even extends it at all.
SortedList handles the communication to the Recycler adapter via Callback.
Ways it Differs from ListView.
- Batching of Update - One difference between SortedList and List is seen in the addAll helper method in the sample below.
Its smart about when to update the Views - When the fetchedItems are added, onChange will only be called if one or more of the Page’s title changed. You can customize what SortedList looks for in the Callback’s areContentsTheSame.
Can manage the ordering of items using comparison. The
compare(Object o1, Object o2)method helps you tell sortedList exactly the way items should be arranged,
areItemsTheSame(Object item1, Object item2)and
areContentsTheSame(Object, Object)to decide whether it should of change should be notify the recyclerview of change or not.
Caching (Keeps last added item) - Say I have 10 cached items to load immediately when my recycler list is populated. At the same time, I query my network for the same 10 items because they could have changed since I cached them. I can call the same addAll method and SortedList will replace the cachedItems with fetchedItems under the hood (always keeps the last added item).
Enough ! It’s Code Time.
Pretty good reasons to use sortedList Right. Using SortedList can be asSimple as:
… here’s the
and the adapter
yea, it can be as easy as that.
compare(Object o1, Object o2) is very helpful in handling the order items are presented. All you have to do is implement your ordering logic by comparing items. More on Comparator
SortedListAdapterCallback, which takes a
RecyclerView.Adapter as a constructor parameter and handles the onInserted() and kin methods for you.
SortedList is in v7
If the sorting criteria of your items may change, make sure you call appropriate methods while editing them to avoid data inconsistencies.
You can control the order of items and change notifications via the
I would love to know if this article helped anyone and I honestly want to see wonderful stuff it helped you churn out.
Belvi - I Beliv