【问题标题】:Firestore pagination with Jetpack Paging 3 - startBefore not loading the correct page使用 Jetpack Paging 3 进行 Firestore 分页 - startBefore 未加载正确的页面
【发布时间】:2021-03-22 03:52:03
【问题描述】:

这是我尝试使用 Paging 3 对 Firestore 聊天消息集合进行分页。它正确加载了下一页,因此 startAfter 运算符似乎按预期工作。但它没有正确加载以前的页面。相反,它总是再次加载第一页并将其附加到列表的开头。 (我在 100 个项目后开始丢弃页面,因此延迟加载在两个方向都有效)。

prevKey 似乎传递正确。在我们构建查询之前,它在加载方法的开头具有正确的值。

timeStamp 是带有 @ServerTimestamp 注释的 Firestore 服务器时间戳(如果重要)。

class ChatMessagesPagingSource(
    private val messageCollection: CollectionReference
) : PagingSource<ChatMessagesPagingSource.PagingKey, ChatMessage>() {

    override suspend fun load(params: LoadParams<PagingKey>): LoadResult<PagingKey, ChatMessage> {
        return try {

            var query = messageCollection
                .orderBy("timeStamp", Query.Direction.DESCENDING)
                .limit(params.loadSize.toLong())

            val key = params.key

            Timber.d("key = $key")

            query = when (key) {
                is PagingKey.PreviousKey -> query.endBefore(key.endBefore)
                is PagingKey.NextKey -> query.startAfter(key.startAfter)
                null -> query
            }

            val querySnapshot = query.get().await()
            val chatMessages = querySnapshot.toObjects(ChatMessage::class.java)
            val firstDoc = querySnapshot.documents.firstOrNull()
            val lastDoc = querySnapshot.documents.lastOrNull()
            val prevKey = if (firstDoc != null) PagingKey.PreviousKey(firstDoc) else null
            val nextKey = if (lastDoc != null) PagingKey.NextKey(lastDoc) else null

            Timber.d("first message: ${chatMessages.firstOrNull()}")
            Timber.d("last message: ${chatMessages.lastOrNull()}")

            LoadResult.Page(
                data = chatMessages,
                prevKey = prevKey,
                nextKey = nextKey
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    sealed class PagingKey{
        data class PreviousKey(val endBefore: DocumentSnapshot) : PagingKey()
        data class NextKey(val startAfter: DocumentSnapshot) : PagingKey()
    }
}

【问题讨论】:

    标签: firebase kotlin google-cloud-firestore android-paging android-paging-library


    【解决方案1】:

    您需要检查 LoadParams 的类型,看看它是刷新、前置还是附加。

    由于您的查询始终按降序获取项目,因此当它请求前置时,您可能加载了不正确的项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多