在Firestore中使用分页时,如何获取正确的newIndex? [英] How to get the correct newIndex when using pagination in Firestore?

查看:56
本文介绍了在Firestore中使用分页时,如何获取正确的newIndex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经根据文档实施了分页.我在我的项目中使用以下代码:

I have implemented pagination according to the docs. I'm using this code in my project:

override fun onEvent(querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
    if (e != null) return

    for (documentChange in querySnapshot!!.documentChanges) {
        value = when (documentChange.type) {
            Type.ADDED -> {
                Log.d("TAG", "oldIndex:" + documentChange.oldIndex + "/" + "newIndex:" + documentChange.newIndex)
            }
            Type.MODIFIED -> {
                Log.d("TAG", "oldIndex:" + documentChange.oldIndex + "/" + "newIndex:" + documentChange.newIndex)
            }
            Type.REMOVED -> {
                Log.d("TAG", "oldIndex:" + documentChange.oldIndex + "/" + "newIndex:" + documentChange.newIndex)
            }
        }
    }
}

当我使用此查询获取前4个用户时:

When I'm using this query to get the first 4 users:

var query: Query = db.collection("users")
    .orderBy("name", DESCENDING)
    .limit(4)

我得到:

A/oldIndex:-1/newIndex:0
B/oldIndex:-1/newIndex:1
C/oldIndex:-1/newIndex:2
D/oldIndex:-1/newIndex:3

这是正确的,因为所有用户都是新用户,并且oldIndex等于-1.newIndex从0递增到3,这也是正确的.但是,当我使用此查询时:

Which is correct, since all the users are new and have the oldIndex equal to -1. The newIndex is incremented from 0 to 3 which is also correct. However, when I'm using this Query:

var secondQuery: Query = db.collection("users")
    .orderBy("name", DESCENDING)
    .startAfter(lastVisibleUser)
    .limit(4)

要获得接下来的4位用户,我得到:

To get the next 4 users, I get:

E/oldIndex:-1/newIndex:0
F/oldIndex:-1/newIndex:1
G/oldIndex:-1/newIndex:2
H/oldIndex:-1/newIndex:3

用户名正确的地方,oldIndex还是正确的,但是newIndex应该从0开始,不是从4开始.我如何第二次获得正确的newIndex?

Where the name of the users is correct, the oldIndex is again correct, but the newIndex starts from 0 and not from 4 as it should be. How can I get the correct newIndex, second time?

推荐答案

将为快照获取的索引与同一侦听器的先前快照进行比较.由于您触发了一个新查询,因此它是一个新的侦听器,因此所有索引都基于一个空的先前状态.

The indexes that you get for snapshots are compared to the previous snapshot of the same listener. Since you fire a new query, it is a new listener, and so all indexes are based on an empty previous state.

要查看索引的作用如何工作,请在查询中附加一个永久侦听器,然后在第一个查询中更改其中一个用户的名称,以使其更改其在结果中的位置.您将看到所有用户的先前索引和新索引将根据先前快照和新状态进行更新.

To see how indexes do work, attach a permanent listener to the query, then change the name of one of the users in the first query so that it changes its location in the results. You'll see the previous and new index for all users be updated based on the previous snapshot and the new state.

这篇关于在Firestore中使用分页时,如何获取正确的newIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆