PeterPazmandi
PeterPazmandi

Reputation: 581

Firestore Pagination doesn't work in Android

I would like to fetch the documents using the Firestore pagination, but it starts all the time from the beginning.

I have already created the index for the query of whereArrayContains and orderBy. So it works perfectly when I fetch the first 10 records.

But when I would like to fetch the next 10 result, then I get back the first 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)

enter image description here

Upvotes: 0

Views: 180

Answers (1)

PeterPazmandi
PeterPazmandi

Reputation: 581

Finally I have found the solution.

I'm passing the lastShoppingListResult variable as a nullable object into the .startAfter() method.

I had to cast it directly to a non nullable DocumentSnapshot. In this case the request works perfectly.

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

Upvotes: 1

Related Questions