【发布时间】:2021-04-08 09:00:42
【问题描述】:
我最近迁移到 Paging3。但是,我注意到大部分教程和指南主要是在正常分页上(从上到下)。
当用户滚动到顶部边界时,我需要实现 REVERSE 分页,将加载页面 2,3,4.. 有这方面的教程/指南吗?
PS:现在初始加载工作正常,但是当我滚动到最顶部时,我不知道如何加载 Page 2 数据。
我目前的做法
分页源
class ChatPagingSource(
private val apiService: ApiService,
private val roomId: String
): PagingSource<Int, Message>() {
override fun getRefreshKey(state: PagingState<Int, Message>): Int? = null
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Message> {
return try{
val page = params.key?: 1
val pageSize = params.loadSize
val call = apiService.getMessageFeedPaging(
room_id = roomId,
page = page,
max = pageSize,
exclude = EXCLUDE_TYPE
)
val repoItems = call.messages
val prevKey = if(page > 1) page - 1 else null
val nextKey = if(repoItems.isNotEmpty()) page + 1 else null
if(repoItems.isNotEmpty()) {
val messageList = mutableListOf<Message>()
for (i in repoItems) {
val replyData = Converters.convertReplyDataAPItoReplyData(i.reply_data)
val msg = Converters.convertMessageAPItoMessage(replyData, i, hasError = false)
messageList.add(msg)
}
LoadResult.Page(messageList, prevKey, nextKey)
} else {
LoadResult.Page(listOf(), prevKey, nextKey)
}
}catch (e: Exception) {
LoadResult.Error(e)
}
}
}
存储库
fun loadRemoteMessageStream(roomId: String): LiveData<PagingData<Message>> {
return Pager(
config = PagingConfig(20),
pagingSourceFactory = { ChatPagingSource(apiService, roomId) }
).liveData
}
视图模型
private val _remoteMessage = chatRepository.loadRemoteMessageStream(currentRoomId)
.cachedIn(viewModelScope)
.let { it as MutableLiveData<PagingData<Message>> }
val remoteMessage: LiveData<PagingData<Message>> = _remoteMessage
片段
chatViewModel.remoteMessage.observe(viewLifecycleOwner, {
chatAdapter.submitData(viewLifecycleOwner.lifecycle, it)
})
【问题讨论】:
标签: android-paging-3