【问题标题】:How to remove the observer on the path in Firestore?如何删除 Firestore 路径上的观察者?
【发布时间】:2020-01-02 15:01:34
【问题描述】:

我有一个聊天室 ID 列表,我想在每个聊天室 ID 上添加快照侦听器。这是通过循环所有聊天室 id 并在每个聊天室 id 上添加观察者来添加的,如下所示:

private func addObserverOnEachChatRoom(data: [ChatListInfo]) {
    for chatInfo in data {
        if let roomId = chatInfo.chatRoomId,
            !roomId.isEmpty {
            self.addObserverOnChatRoomToFetchLastMessage(roomId: roomId)
        }
    }
}

//add observer on a chat room id
func addObserverOnChatRoomToFetchLastMessage(roomId: String, completion: @escaping (_ lastMessage: Message) -> Void, failure: (_ error: Error) -> Void) {
    self.messageListener = self.chatsFirestoreRef.document(roomId).collection("messages").order(by: "time").addSnapshotListener { (snapshot, error) in
        guard error == nil else {
            //FIXME: Handle the error here
            return
        }
        if let document = snapshot?.documents.last?.data() {
            do {
                let jsonData = try JSONSerialization.data(withJSONObject: document, options: .prettyPrinted)
                let message = try JSONDecoder().decode(Message.self, from: jsonData)
                completion(message)
            } catch (let error) {
                DILog.print(items: error.localizedDescription)
            }
        }
    }
}

如何删除特定聊天 ID 上的侦听器?在 firebase 中,我们可以遍历到节点的路径并删除该节点上的观察者,但在 Firestore 中,如果观察者被添加到多个项目的循环中,我如何引用特定的集合。

【问题讨论】:

  • if else 条件:D

标签: ios swift google-cloud-firestore chat


【解决方案1】:

当您添加观察者时,API 会返回一个句柄,您可以使用该句柄来取消订阅。来自documentation

let listener = db.collection("cities").addSnapshotListener { querySnapshot, error in
    // ...
}

// ...

// Stop listening to changes
listener.remove()

由于您有多个观察者,每个聊天室 id 一个,您需要按聊天室 id 保存这些听众的字典。

var listenersByChatRoomId: [String, String] = [:];

...

listenersByChatRoomId[roomId] = self.messageListener;

然后您可以通过以下方式取消订阅特定房间的更新:

listenersByChatRoomId[roomId].remove()
listenersByChatRoomId[roomId] = nil

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多