After attending this session at Google IO 18, it inspired me to look at little deeper into the new paging adapter. We currently ship a database with our app which contains all the postcodes in Australia and instead of loading 18,000+ records into memory when a user searches for a postcode we thought it would be far more efficient if we loaded 1500 records at a time.
The example I use in this article builds upon the code that I published in another article a few months ago which appeared on AndroidWeekly.net
Let's get started.
Step 1. Change the query in the Dao
object to return the new DataSource
class. The Factory takes 2 parameters the primary key of the table and the data class.
Step 2. The next major change to our code involves using the DiffUtil.ItemCallBack
in our RecyclerView
adapter. The DiffUtil.ItemCallBack
merges the different pages together so the list scrolls seamlessly for the user. If a page hasn’t been fully loaded yet, the user is shown a skeleton view of the item.
Step 3. The last step in our solution involves initializing the paging adapter in the UI activity. As we use RxJava extensively in our app we decided to use the RxPagedListBuilder
. Using the builder we configure the page size and set placeholders on so a skeleton view is displayed while the page is being loaded. If you use LiveData
, the LivePagedListBuilder
is just as easy to use.
A few important tips to note, as the user changes the search criteria we must create a new paging adapter each time to clear the results and also debounce the text changes to limit the number of paging adapters we create to avoid any threading issues.
Before
After
Notice that the screen loads so fast that the spinner isn’t shown.
Conclusion
So, there you go in just 3 easy steps we added the paging adapter to our app. We’ve got faster screen loads and a less resource hungry app.