How can I observe Firebase child value changes in multiple nodes in Swift?

Radagast the Brown picture Radagast the Brown · Jul 18, 2017 · Viewed 7.8k times · Source

I have a "users" node in my Firebase database. Each user in it has a root with a uid for it. One of the properties of each user is "coordinates". I want to observe any change in any of those coordinates for all users. I almost need something like:

usersDatabaseReference.child("*").child("coordinates").observe(.value, with: { (snapshot) in 

My structure looks like this:

  • users

    • abcdefghijklmnop

      • coordinates: "12.345,12.345"

      • other props

    • qrstuvwxyz

      • coordinates: "34.567,34.567"

      • other props

So I'm looking for a global notification for any user whose coordinates value changes.

Do I need to loop through all children in my userDatabaseReference and set observers for each? And then any time a user is added or removed, set it all up again?

You can see why I'd like to use a wildcard. How should I approach this?

Answer

Jay picture Jay · Jul 18, 2017

You could just observe the users structure as a whole, then use the snapshot to determine if the coordinate is the element that has changed

usersDatabaseReference.child("users").observe(.childChanged, with: { (snapshot) in
        //Determine if coordinate has changed
 })

What you could also do is :

func observeChildAdded(){
    usersDatabaseReference.child("users").observe(.childAdded, with: { (snapshot) in
        //Get the id of the new user added
        let id = "123"
        self.usersDatabaseReference.child("users").child(id).observe(.childChanged, with: { (snapshot) in
            self.foundSnapshot(snapshot)
        })
    })
}

func foundSnapshot(_ snapshot: DataSnapshot){
    let idChanged = snapshot.key
    //Process new coordinates
}

So that whenever you add a new child it automatically sets up an observer for it, but they all get pushed to the same function foundSnapshot