Skip to content

Instantly share code, notes, and snippets.

@eliasbagley
Created April 11, 2017 19:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliasbagley/29f5a7b1ba1cffa53c75a366175932d6 to your computer and use it in GitHub Desktop.
Save eliasbagley/29f5a7b1ba1cffa53c75a366175932d6 to your computer and use it in GitHub Desktop.
RxJava endless scroll listener
package com.example;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import io.reactivex.Observable;
import io.reactivex.subjects.BehaviorSubject;
/**
* Created by eliasbagley on 3/29/17.
*/
public class EndlessScroll {
private boolean loading = false;
private int pastVisiblesItems;
private int visibleItemCount;
private int totalItemCount;
private LinearLayoutManager layoutManager;
private BehaviorSubject<Object> onLoadMore = BehaviorSubject.create();
// extended from http://stackoverflow.com/questions/26543131/how-to-implement-endless-list-with-recyclerview
public EndlessScroll(RecyclerView recyclerView, LinearLayoutManager manager) {
this.layoutManager = manager;
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) { // scroll down
visibleItemCount = layoutManager.getChildCount();
totalItemCount = layoutManager.getItemCount();
pastVisiblesItems = layoutManager.findFirstVisibleItemPosition();
// if we're not currently loading data and we're near the end of the list, then trigger a load
if (!loading && isNearEnd()) {
setLoading(true);
loadMore();
}
}
}
});
// trigger off a request so the list will start with a page of data
loadMore();
}
public synchronized void setLoading(boolean loading) {
this.loading = loading;
}
public Observable<Object> onLoadMore() {
return onLoadMore;
}
// region private methods
private void loadMore() {
onLoadMore.onNext(1);
}
private boolean isNearEnd() {
// start a load once we're 90% down the list
return (pastVisiblesItems + visibleItemCount >= (0.90 * totalItemCount));
}
//endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment