Android Paging Library tutorial with Retrofit using MVVM Architecture.

Last Year Google announced android jetpack components, Paging library is one of them. There are lots of advantages, Suppose you have 5000 images data from a backend API and you do not want load whole 5000 images data at once that time you can use the paging library. This only load small amounts of data from your large data set. It will consume less bandwidth. Also, fewer resources resulting in a smooth app and nice user experience.

So lets Started…

We will parse data from this link https://jsonplaceholder.typicode.com/photos

We will separate page by "albumId"

Include these dependencies on your gradle.build file.

def lifecycle_version = "1.1.1"

// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

First, create a model class. You must put this class under model Package.

Add Retrofit dependency in gradle file.

Now Create the Retrofit Instance

Now create an Interface for “GET ”method via Retrofit

Now we need to create a PhotoDataSource class under the model package Which will extend PageKeyedDataSource<> Class. Here Three methods should override loadInitial , loadBefore and loadAfter. We need to call retrofit from loadInitial and loadAfter method.

Now we need to create a PhotoDataSourceFactory class under the model package which will extends DataSource.Factory class.

Now need to create a ViewModel class under viewmodel Package and call getMutableLiveData() method from PhotoDataSourceFactory class. Here we need 2 new things. PagedList and Executor. We need to configure PagedList and set Executer for Background threads.

We need to modify our model class. We need to add a DiffUtil Callback here. New class should look like this.

Now create a PagedListAdapter under Adapter Package. I am creating a photoAdapter class and extends PagedListAdapter<>.

Now in MainActivity, we will set adapter with recyclerView. Before set Adapter, we will submitList() our PageList data. We use a LiveData Observer for getting pagedList Data. After getting data and notified in callback we need to set photosAdapter.submitList(photos); before setting Adapter.

That's it…

Here is the Layout files.

activity_main.xml

list_photos.xml

Here is my project file Structure.

Project File Structure (MVVM).

Software Engineer