android - Firestore 分页在 Android 中不起作用
问题描述
我想使用 Firestore 分页来获取文档,但它总是从头开始。
我已经为whereArrayContains
和的查询创建了索引orderBy
。因此,当我获取前 10 条记录时,它可以完美运行。
但是当我想获取下一个 10 个结果时,我会取回前 10 个。
override suspend fun getShoppingLists(
currentUser: User, coroutineScope: CoroutineScope
) = flow<Resource<MutableList<ShoppingList>>> {
emit(Resource.Loading(true))
val result = if(lastShoppingListResult == null) {
shoppingListsCollectionReference
.whereArrayContains(FRIENDSSHAREDWITH, currentUser.id)
.orderBy(DUEDATE, Query.Direction.DESCENDING)
.limit(LIMIT_10)
.get()
.await()
} else {
shoppingListsCollectionReference
.whereArrayContains(FRIENDSSHAREDWITH, currentUser.id)
.orderBy(DUEDATE, Query.Direction.DESCENDING)
.startAfter(lastShoppingListResult)
.limit(LIMIT_10)
.get()
.await()
}
val documentsList = result.documents
if (documentsList.size > 0) {
lastShoppingListResult = documentsList[documentsList.size - 1]
}
val listOfShoppingList = mutableListOf<ShoppingList>()
for (document in documentsList) {
val shoppingList = document?.toObject(ShoppingList::class.java)
shoppingList?.let {
listOfShoppingList.add(shoppingList)
}
}
emit(Resource.Success(listOfShoppingList))
}.catch { exception ->
exception.message?.let { message ->
emit(Resource.Error(message))
}
}.flowOn(Dispatchers.IO)
解决方案
最后我找到了解决方案。
我将lastShoppingListResult
变量作为可空对象传递给.startAfter()
方法。
我不得不将它直接转换为不可为空的DocumentSnapshot
. 在这种情况下,请求可以完美运行。
...
.startAfter(lastShoppingListResult as DocumentSnapshot)
...
推荐阅读
- node.js - 将节点终端/main.js 日志打印到渲染器控制台(开发人员工具)
- azure - Azure 文件共享 – 无法从 Azure 文件共享中删除文件
- python - 命令“/bin/sh -c pip install --upgrade pip && pip install requests”返回非零代码:127
- python - 将嵌套字典中的 csv_rows 与计数相结合
- php - codeigniter 4中的模块和语言
- python - 如何计算我的句子列表中每个句子的正面和负面词的数量?
- regex - 在整个项目的搜索/替换对话框中更改大小写
- sql-server - 查询末尾的“ON”是什么?
- javascript - Discord.js V12 如何锁定某个角色的所有频道?
- ios - FCM 令牌或 APNS 令牌不适用于 iOS 上的 Firebase 通知