Skip to content

Instantly share code, notes, and snippets.

@gordinmitya
Created January 30, 2017 14:54
Show Gist options
  • Save gordinmitya/d46d2254d9287f631adda93b6ccdb03d to your computer and use it in GitHub Desktop.
Save gordinmitya/d46d2254d9287f631adda93b6ccdb03d to your computer and use it in GitHub Desktop.
Бесконечный скролл RxKotlin Android
class EndlessList {
companion object {
fun <T> get(recyclerView: RecyclerView, next: (Int) -> Observable<Response<T>>): Observable<Response<T>> {
var loading = false
var hasNextPage = true
return Observable.create<Int> {
val lm = recyclerView.layoutManager
val getLastVisible = if (lm is LinearLayoutManager) {
fun() = lm.findLastVisibleItemPosition()
} else if (lm is GridLayoutManager) {
fun() = lm.findLastVisibleItemPosition()
} else {
throw Exception("LayoutManager must be Linear or Grid")
}
if (lm.itemCount == 0) {
it.onNext(0)
}
val scrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (dy <= 0) return
if (!hasNextPage) {
it.onCompleted(); recyclerView?.removeOnScrollListener(this); return
}
val position = getLastVisible()
val updatePos = lm.itemCount - 3
if (!loading && position > updatePos) {
it.onNext(lm.itemCount)
}
}
}
recyclerView.addOnScrollListener(scrollListener)
}
.doOnNext {
loading = true
//fixme cleanup log
Log.i("EndlessList", "offset $it")
}
.switchMap(next)
.doOnNext {
loading = false
hasNextPage = it.hasNextPage
var size = 1
if (it.data is List<*>) {
size = it.data.size
}
Log.i("EndlessList", "next $size ${it.hasNextPage}")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment