我有一个Chat ViewController和一个ChatList
每当我点击聊天列表上的对话时,我会计算所有孩子的总数并保存聊天大小(消息数量)。
然而,似乎观察者函数被调用了两次并且弄乱了我真实的聊天大小。
let messagesChannelRef = mainChannelRef.child(channelid).child("messages")
messagesChannelRef.observe(FIRDataEventType.value, with: { (snapshot: FIRDataSnapshot) -> Void in
UserDefaults.standard.set(snapshot.childrenCount, forKey: "latestreadchatsize@\(channelid)")
UserDefaults.standard.synchronize()
})
如何避免两次调用的观察函数?
更新的问题:
以下是我使用的代码..
class ChannelListTableViewController: UITableViewController {
...........
...........
private lazy var channelRef: FIRDatabaseReference = FIRDatabase.database().reference().child("channels")
..........
func showChatDialog(channelObj: Channel){
let navChatVc: UINavigationController = self.storyboard?.instantiateViewController(withIdentifier: "navChatView") as! UINavigationController
let chatVc : ChatViewController = navChatVc.viewControllers.first as! ChatViewController
chatVc.senderDisplayName = senderDisplayName
chatVc.channel = channelObj
chatVc.channelRef = channelRef.child(channelObj.id)
let channelid = channelObj.id
let messagesChannelRef = channelRef.child(channelid).child("messages")
self.present(navChatVc, animated:true, completion: { () -> Void in
let channelid = channelObj.id
channelRef.child(channelid).child("messages").observe(FIRDataEventType.value, with: { (snapshot: FIRDataSnapshot) -> Void in
UserDefaults.standard.set(snapshot.childrenCount, forKey: "latestreadchatsize@\(channelid)")
UserDefaults.standard.synchronize()
})
})
}
...........
...........
} //end of class
每当点击showChatDialog时,它实际上只调用一次但是当我从另一个客户端发送聊天消息时,则会调用observe函数两次?
我知道聊天客户端互相调用新消息。因此,当使用新消息更新Firebase时,我想它会重新调用observe函数,这意味着它会监听任何更新?
答案 0 :(得分:3)
解决方案更新
最后,用2种可能的方式找到答案
ObserveSingleType
或删除FIRDatabaseHandle观察员
//检查单个频道的总邮件大小
//you can choose one of these 2 ways
let mainChannelRef: FIRDatabaseReference = FIRDatabase.database().reference().child("channels")
//1st way
if let channelid = channel?.id {
mainChannelRef.child(channelid).child("messages").observeSingleEvent(of: .value, with: { (snapshot) in
UserDefaults.standard.set(snapshot.childrenCount, forKey: "latestreadchatsize@\(channelid)")
UserDefaults.standard.synchronize()
})
}
//2nd way
if let channelid = channel?.id {
let newRefHandle: FIRDatabaseHandle = mainChannelRef.child(channelid).child("messages").observe(FIRDataEventType.value, with: { ( snapshot: FIRDataSnapshot) -> Void in
UserDefaults.standard.set(snapshot.childrenCount, forKey: "latestreadchatsize@\(channelid)")
UserDefaults.standard.synchronize()
})
mainChannelRef.child(channelid).child("messages").removeObserver(withHandle: newRefHandle)
}
它们都确保只点击观察者一次