从自定义分页实现迁移到Jetpack分页3库后,数据没有按预期加载。首页根据PagingConfig of Pager正确处理Pager
internal fun createProductListPager(pagingSource: ProductListPagingSource): Pager<Int, Product> = Pager(
    config = PagingConfig(
        pageSize = 10,
        prefetchDistance = 2,
    ),
    initialKey = 0,
) { pagingSource }以下是Adapter的摘录
public class PagingProductCardAdapter(private val viewBinder: CoreViewBinder) :
    PagingDataAdapter<Listable, RecyclerView.ViewHolder>(viewBinder.getDiffUtils()) {
    public val list: List<Listable>
        get() = snapshot().items
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
      // ...
    }
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        viewBinder.bind(list[position], holder)
    }
    // ...
}当滚动到RecyclerView的底部时,下一页是没有加载在所有(不调用PagingSource.load()),什么会出错?
发布于 2022-04-06 08:57:43
PagingSource如何知道何时加载更多数据?背后是什么魔法?
实际上,--适配器--负责这个。Adapter如何才能知道已加载的数据?您必须按文档所示调用getItem():
/**
 * Returns the presented item at the specified position, notifying Paging of the item access to
 * trigger any loads necessary to fulfill [prefetchDistance][PagingConfig.prefetchDistance].
 *
 * @param position Index of the presented item to return, including placeholders.
 * @return The presented item at [position], `null` if it is a placeholder
 */
protected fun getItem(@IntRange(from = 0) position: Int) = differ.getItem(position)当我们通过快照访问整个列表时:
public val list: List<Listable>
    get() = snapshot().items适配器无法知道正在加载哪些项,也无法触发下一个页面加载。
所以解决办法是:
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    getItem(position)?.let {
        viewBinder.bind(list[position], holder)
    }
}有了这个,一切都正常了!
https://stackoverflow.com/questions/71763828
复制相似问题