Android Paging v3 实现分页时RecyclerView列表项重复加载问题求助
问题根因及修复方案
1. 分页查询缺少偏移量,每次拉取的都是前N条数据
你当前的Dao查询只做了条数限制,没有根据当前页码计算偏移量,不管加载第几页,永远返回数据库最新的前params.loadSize条数据,每翻一页就会把前面的内容重复追加到列表中,这是数据重复的核心原因。
修改方案:
给Dao新增偏移量参数:
@Query("SELECT * FROM notifications ORDER BY createdAt DESC LIMIT :size OFFSET :offset") fun fetchNotifications(size: Int, offset: Int): List<Notifications>
在NotificationsPagingSource的load方法中传入计算好的偏移量:
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Notifications> { val position = params.key ?: INITIAL_PAGE_INDEX // 计算当前页偏移量 val offset = position * params.loadSize val randomNotifications : List<Notifications> = useCase.fetchNotifications(params.loadSize, offset) return LoadResult.Page( data = randomNotifications , prevKey = if (position == INITIAL_PAGE_INDEX) null else position - 1, nextKey = if (randomNotifications.isEmpty()) null else position + 1 ) }
2. 分页终止判断逻辑错误,导致无限加载
你代码中判断nextKey时误用了不存在的变量randomAlerts,导致分页终止条件永远不生效,nextKey永远返回有效值,Paging会一直触发下一页加载,不停往列表追加重复数据。
这个问题的修复已经包含在上面的代码修改中,把判断变量替换为实际的查询结果randomNotifications即可。
3. 其他可优化的错误配置
- PagingConfig的pageSize设为1过于极端,会导致分页请求非常频繁,建议根据列表一屏展示的数量设置合理值,比如10:
val alertListFlow = Pager(PagingConfig(pageSize = 10, enablePlaceholders = false)) { NotificationsPagingSource(useCase) }.flow.cachedIn(viewModelScope) - 差分回调
NotificationsEntityDiff的areContentsTheSame方法参数类型有误,第一个参数应该是Notifications而不是Alert,否则会导致差分计算异常:override fun areContentsTheSame(oldItem: Notifications, newItem: Notifications): Boolean = oldItem == newItem
内容的提问来源于stack exchange,提问作者Kiran
相关产品推荐
相关产品推荐

