我正在编写一个iOS聊天应用程序,我在用户向上滚动时重新加载下面的50条消息。这需要删除查询中的上一个观察者,并注册一个具有新限制的新查询。
然而,有时(并非所有时间!)当我执行此更改时,查询会被触发两次。我意识到,当我删除queryOrderedByChild
并使用queryLimited
时,不会发生此行为。
这是我的代码:
// Before this function is called I removed the handle at the query
func reobserveChatMessages(limit: UInt, connection: Connection, completed: @escaping (_ isSuccess: Bool, _ connection: Connection?) -> ()) -> (FIRDatabaseQuery, FIRDatabaseHandle) {
let uid = getStoredUid() == nil ? "" : getStoredUid()!
let chatId: String = getChatId(uid1: uid, uid2: connection.uid)
let ref: FIRDatabaseReference = REF_MESSAGES.child(chatId)
// Query with a new limit
let q: FIRDatabaseQuery = ref.queryOrdered(byChild: "timestamp").queryLimited(toLast: limit)
let handle = q.observe(.value, with: { snapshot in
let conn = self.processChatSnapshot(snapshot: snapshot, connection: connection, uid: uid)
completed(conn != nil, conn)
})
return (q, handle)
}
如果有帮助,我正在使用FIRDatabase.database().persistenceEnabled = true
。
编辑:奇怪的是,当我删除持久性时,这个问题就消失了。如何保持持久性但仍然执行上述操作?