英文:
Firebase removeObserver is not working in Swift 5
问题
我在我的应用程序中使用Firebase的实时数据库。我从数据库中获取数据并进行一些更改,然后我移除观察者,但这没有正常工作。
我在实时数据库中有一些数据,像这样:
我使用Firebase的observe(.value)函数获取这个值,然后我更新一个条目,然后我移除观察者。这是我的代码:
func updatePoints() {
let firebaseId = UserDefaults.standard.value(forKey: "firebaseId") as? String ?? ""
let reference = self.database.child("Points").child(firebaseId)
var handler : UInt = 0
handler = reference.observe(.value, with: { snapshot in
guard let userPoints = snapshot.value as? [String : Any] else {
print("no points data found")
return
}
let pointsLeft = userPoints["points_left"] as? Int ?? 0
reference.child("points_left").setValue(pointsLeft - 1)
reference.removeObserver(withHandle: handler)
})
}
现在的问题是,这个观察者运行两次。例如,如果**"points_left" : 10**,那么在这个函数之后,剩余的点数将变成8,但实际上应该是9。它运行两次,我不明白为什么会这样,因为我使用了removeObserver。有人可以帮助我吗?
英文:
I am using Firebase's Realtime database in my app. I am fetching data from the database and do some change and after that I am removing the observer which is not working fine.
I have some data in Realtime Database like this:
I am using firebase's observe(.value) function to get this value and after that I am updating an entry and then I am removing the observer. This is my code:
func updatePoints() {
let firebaseId = UserDefaults.standard.value(forKey: "firebaseId") as? String ?? ""
let reference = self.database.child("Points").child(firebaseId)
var handler : UInt = 0
handler = reference.observe(.value, with: { snapshot in
guard let userPoints = snapshot.value as? [String : Any] else {
print("no points data found")
return
}
let pointsLeft = userPoints["points_left"] as? Int ?? 0
reference.child("points_left").setValue(pointsLeft - 1)
reference.removeObserver(withHandle: handler)
})
}
The problem now is, this observer runs twice. For example, if "points_left" : 10, then after this function the points left will have 8 value but it should have 9 instead. It is running twice and I am not understanding why is it doing so as I am using removeObserver. Can someone help me with this?
答案1
得分: 0
上述意外行为的原因是你调用的setValue
函数来更新点数会触发数据库中的另一个.value
事件。然后再次触发观察者。因此,当你移除观察者时,它已经触发了两次。这导致点数减少了2而不是1。
所以,如果你交换最后两行,当你调用setValue
函数时,观察者已被移除。因此,它不会第二次触发。
英文:
The reason to the above unexpected behaviour is the setValue
function you called to update the points is triggering another .value
event in the database. Then it triggers the observer again. Therefore, by the time you remove the observer, it has already triggered twice. This leads to decrease of points by 2 instead of 1.
So if u interchange the last two lines, by the time you call the setValue
function observer is removed. So it will not get triggered for the second time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论