As a developer, we need to fetch data from api call and binds the data into RecyclerView. Sometimes, we need to fetch a huge amount of data from api call and bind them into RecyclerView. If we want to fetch all the data at a time, it will be a very time consuming process and therefore result in a bad user experience. Here comes the use of pagination. We will not load all the data at a time rather we will fetch data as in chunks or pages.

Suppose, we have around 200 data to load from remote server. We will fetch 10 data(varies how your server sends data) at a time and when we reach at the end of the RecyclerView by scrolling, we will fetch next 10 data and this will continue until all the data have been loaded.

First, we will create an interface with a single method.  

public interface ScrollEndListener {

    void onScrollEnd(int position);

}

Inside RecyclerViewAdapter do the following.

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Object> data;
    private LayoutInflater inflater;
    private ScrollEndListener scrollEndListener;

    RecyclerViewAdapter(Context context, List<Object> data, ScrollEndListener scrollEndListener) {
    
        this.inflater = LayoutInflater.from(context);
        this.data = data;
        this.scrollEndListener = scrollEndListener;
    }
    
    //...
}

When the item position inside onBindViewHolder will be the last element, then we can ensure we have reached the end of the RecyclerView and can send a callback using the scrollEndListener interface to load more data.

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {

    ((ViewHolderForEachItem)viewHolder).bindData(data.get(position));
    if (position == data.size() - 1){
    	scrollEndListener.onScrollEnd(position);
    }
    
}

Now, we will initiate the RecyclerViewAdapter in our Activity or Fragment where we are showing data and implement the ScrollEndListener interface.

RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(this, data, new ScrollEndListener() {

    @Override  
    public void onScrollEnd(int position) {
        //load more data and add the new fetched data to the adapter data list
    }
        
});

We can reuse this ScrollEndListener interface in the app where we need pagination inside RecyclerView.