首页 > 解决方案 > 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)

在此处输入图像描述

标签: androidkotlingoogle-cloud-firestorepagination

解决方案


最后我找到了解决方案。

我将lastShoppingListResult变量作为可空对象传递给.startAfter()方法。

我不得不将它直接转换为不可为空的DocumentSnapshot. 在这种情况下,请求可以完美运行。

...
.startAfter(lastShoppingListResult as DocumentSnapshot)
...

推荐阅读