I am making a completion handler for a function which will return a list of objects. When it return value for first time, it works well. But when any change happen into fire
The code you're using declares stadiums
outside of the observer. This means any time a change is made to the value of the database reference, you're appending the data onto stadiums
without clearing what was there before. Make sure to remove the data from stadiums
before appending the snapshots again:
func getStadiums(complition: @escaping ([Stadium]) -> Void){
var stadiums: [Stadium] = []
let stadiumRef = Database.database().reference().child("Stadium")
stadiumRef.observe(.value, with: { (snapshot) in
stadiums.removeAll() // start with an empty array
for snap in snapshot.children {
guard let stadiumSnap = snap as? DataSnapshot else {
print("Something wrong with Firebase DataSnapshot")
complition(stadiums)
return
}
let stadium = Stadium(snap: stadiumSnap)
stadiums.append(stadium)
}
complition(stadiums)
})
}