Skip to content

Commit

Permalink
Convert InfiniteScrollListener to Kotlin.
Browse files Browse the repository at this point in the history
The Runnable was just too much boilerplate!
  • Loading branch information
nickbutcher committed Nov 10, 2017
1 parent 4d18533 commit 38abd70
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 66 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package io.plaidapp.ui.recyclerview

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView

import io.plaidapp.data.DataLoadingSubject

/**
* A scroll listener for RecyclerView to load more items as you approach the end.
*
* Adapted from https://gist.github.com/ssinss/e06f12ef66c51252563e
*/
abstract class InfiniteScrollListener(
private val layoutManager: LinearLayoutManager,
private val dataLoading: DataLoadingSubject
) : RecyclerView.OnScrollListener() {
private val loadMoreRunnable = Runnable { onLoadMore() }

override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
// bail out if scrolling upward or already loading data
if (dy < 0 || dataLoading.isDataLoading) return

val visibleItemCount = recyclerView.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItem = layoutManager.findFirstVisibleItemPosition()

if (totalItemCount - visibleItemCount <= firstVisibleItem + VISIBLE_THRESHOLD) {
recyclerView.post(loadMoreRunnable)
}
}

abstract fun onLoadMore()

companion object {
// The minimum number of items remaining before we should loading more.
private const val VISIBLE_THRESHOLD = 5
}
}

0 comments on commit 38abd70

Please sign in to comment.