0

我最近迁移到 Paging3。但是,我注意到大多数教程和指南主要是正常分页(从上到下)

当用户滚动到顶部边界时,我需要实现反向分页,将加载页面 2、3、4 .. 是否有任何教程/指南?

PS:现在初始加载工作正常,但是当我滚动到最顶部时,我不知道如何加载第 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)
  })
4

1 回答 1

0

如果这对任何人有帮助,我会发布我自己的答案。关键是反转prevKeynextKey修复您的 API 所需的 pageSize(在我的情况下为 20)。

override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Message> {
    val pageSize = 20
    val prevKey = if(repoItems.isNotEmpty()) page + 1 else null
    val nextKey = if(page > 1) page - 1 else null
}

然后,在 recyclerview 中,您应该使用stackFromEnd = true,以便最初 recyclerview 将自动滚动到底部。

于 2021-05-01T07:31:29.163 回答