Infinite Scrolling // Endlessly scroll with RecyclerView and Unsplash API


A common pattern seen in many apps is infinite or endless scrolling. I thought this was interesting and wanted to take a stab at creating this feature - especially since Unsplash had recently released their API for free (I love exploring new APIs 😀). After digging around the internet a bit, I found a few examples for implementing this feature, but felt like there was an opportunity to create a better jumping off point for someone looking to implement this feature for themselves.

So for my demo, I used

  • MVP architecture
  • Retrofit - HTTP client for networking
  • Glide - Image loading library

Disclaimer, I wrote the original code back in March 2017, but I think it still holds up.

Much of the demo app is skeleton and meant to be built upon or used as a reference, hence the MVP design. You'll also find some placeholder methods that haven't been implemented yet, eg.

Infinite Scroll Listener

The key mechanism here is the custom scrollListener which extends RecyclerView.OnScrollListener. This will allow you to set a threshold on your recyclerView to signal when to load more data. In this demo, the InfiniteScrollListener will look for the last visible view and add the threshold number to it (in our case it's 5 items) and check if that sum is greater than the total number of items. If it is, we'll load more data. Here's the full InfiniteScrollListener code to illustrate better:

Then you just need to add the InfiniteScrollListener to your recyclerView. Once the threshold is met, the InfiniteScrollListener's abstract onLoadMore() method will be called, which will let the presenter know to fetch more images from Unsplash. 

Retrofit Interceptors

Retrofit has a tool called interceptors that can be chained together to perform some powerful operations. In this demo, I used interceptors to send my Client-ID that's required by Unsplash as well as perform caching operations for the data I fetched from the network. You can see how I've implemented the AuthorizationHeaderInterceptor, ResponseCacheInterceptor, and OfflineCacheInterceptor here:

You can find out more about Retrofit's interceptors here.

Final Notes

As this is only a demo app, there is a lot of room for improvements. Implementing Dagger would be helpful for the dependencies as I'm using the singleton pattern within the app, for example. And RxJava may be appropriate and would help to modernize the implementation a bit. Overall, this was a fun project to work on and I hope someone will find it useful. You can find a link to the GitHub repo below.