如何快速正确更改shapshotListener的whereField值?

问题描述

我需要在“ snapshotListener”查询中更改whereField变量值。

即使我在更改前调用代码listener?.remove,根据前一个查询条件的快照也会重新开始监听,而我正在使用新的whereField调用“ shapshotListener”。

同时,根据新查询条件的快照也开始监听。

因此,如果文档有任何更改,我将收到2个不同的快照。

我想用代码来解释:

第1步(认为UserID为111)

listener = Firestore.firestore().collection("Annotations").whereField("UserID",isEqualTo: \(UserID)).addSnapshotListener { (snapshot,error) in

        if error != nil {}else {
            if snapshot?.isEmpty == false && snapshot != nil {
                for document in snapshot!.documents {
                    if let snapshotUserID = document.get("UserID") as? String {

                        print("snapshotUserID: \(snapshotUserID)")
                        print("UserID: \(UserID)")
                    }
                }
            }
        }
    }

第2步

listener?.remove

第3步

UserID = 112

第4步

listener = Firestore.firestore().collection("Annotations").whereField("UserID",error) in

        if error != nil {}else {
            if snapshot?.isEmpty == false && snapshot != nil {
                for document in snapshot!.documents {
                    if let snapshotUserID = document.get("UserID") as? String {

                        print("snapshotUserID: \(snapshotUserID)")
                        print("UserID: \(UserID)")
                    }
                }
            }
        }
    }

现在,两个UserID文档都有2个shapshotListeners。

认为如果用户ID为111的文档中有任何更改,它将在控制台中这样写;

snapshotUserID:111

用户名:1​​12

如何正确更改shapshotListener的查询参数?

解决方法

在附加了侦听器并接收结果的同时,无法更改查询。您现在所要做的就是尽力而为-删除侦听器,构建一个新查询,然后向该查询添加一个新侦听器。如果您不想处理新查询中的任何重复数据,则需要弄清楚如何跳过不想处理的快照。