This story describes about infinite list functionality using Kotlin.

Use case: For instance we are making an webservice call from mobile application to fetch data to be displayed in a RecyclerView. The back end webservice sends 300 or more rows at a time and pagination functionality is not implemented in backend.

Problems with the above use case: The problem with the above use case is we have to populate recyclerview with 300 rows using Adapter which is bad practice as all the elements are not visible at a time on Adapter .It’s not a good practice to populate adapter with 300 rows when user at a time can view maximum of 10 to 20 rows based on available screen height.

Solution for above use case: The above problem can be solved by implementing “Pagination” functionality with in the app .

Steps for Pagination implementation:

(1) Fetch all the rows from backend server using retrofit.

(2) Prepare data from the received data to display only 10 elements at a time on Recycler View.

(3) Implement ViewType functionality in recyclerview adapter : one view type displays 10rows and 11th row is displayed as “Loadmore”

(4) When clicked on “Loadmore” next set of elements are displayed which means 11 to 20 rows with 21st row as “Loadmore”.

(5) The above process is continued till we reach end of all the elements from the data received from webservice .

Sample Screen shots for the above implementation:

Implementation details:

Step 1: Create a data class that represents JSON response from backend. For demo purpose , the data is read from .json file of assets folder that contains 204 records of data.

Step 2: Prepare another model class with ViewTypes to be display data in with RecyclerView Adapter.

Step 3: Prepare data for adapter

Step4: Create an interface to be implemented in fragment to fetch subsequent list items when clicked on “Loadmore” button in Adapter.

Step 5: ViewModel: Contains methods to fetch data from backend (in the sample using .json file located under assets folder ) and prepare data to be displayed in Adapter

Step 6: Adapter -> contains implementation to display data based on view type .

Step 7: Logic to handle upper limit and lower limit of original data list to display 10 rows at a time.

Source code for the above functionality over GitHub:

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store