Reputation: 69
I was using PageKeyedDataSource to get data from network. the data has total 6 pages, pagesize is 10.
val myPagingConfig = PagedList.Config.Builder()
.setPageSize(pageSize)
.setPrefetchDistance(pageSize)
.setInitialLoadSizeHint(pageSize)
.setEnablePlaceholders(false)
.build()
but paging will fire 5 times loadAfter,without scrolling. then whole data will be loaded
Upvotes: 6
Views: 2748
Reputation: 1992
I had same problem because of using RecyclerView
in NestedScrollView
.
if you are in the same situation try remove NestedScrollView
or use this instead of NestedScrollView.
(refer to this answer)
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import androidx.core.view.forEach
import androidx.core.widget.NestedScrollView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
open class SmartNestedScrollView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : NestedScrollView(context, attrs, defStyleAttr) {
override fun measureChildWithMargins(child: View, parentWidthMeasureSpec: Int, widthUsed: Int, parentHeightMeasureSpec: Int, heightUsed: Int) {
if (findNestedRecyclerView(child) != null) {
val lp = child.layoutParams as MarginLayoutParams
val childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
lp.topMargin + lp.bottomMargin, MeasureSpec.AT_MOST
)
child.measure(parentWidthMeasureSpec, childHeightMeasureSpec)
} else {
super.measureChildWithMargins(child, parentWidthMeasureSpec, widthUsed, parentHeightMeasureSpec, heightUsed)
}
}
private fun findNestedRecyclerView(view: View): RecyclerView? {
if (view is RecyclerView) {
val vertical = (view.layoutManager as? LinearLayoutManager)?.orientation == LinearLayoutManager.VERTICAL
if (vertical) return view
}
if (view is ViewGroup) {
view.forEach { child ->
val rv = findNestedRecyclerView(child)
if (rv != null) return rv
}
}
return null
}
}
//reference: https://gist.github.com/danaimset/abacaa50d746a4537686a08ecc33c1a9
Update:
make sure pass null to nextKey
in PagingSource
class if reaching end of data(i.e no more data to load)
override suspend fun load(params: LoadParams<String>): LoadResult<String, Wallpost> {
return try {
val nextPage = params.key ?: url
val response = repository.getPostList(nextPage)
LoadResult.Page(
data = response.list,
prevKey = "",
nextKey = if (response.hasNextPage) response.next else null
)
}catch (e: Exception){
LoadResult.Error(e)
}
}
Upvotes: 3