DoesData
DoesData

Reputation: 7047

Do I need multiple Firebase database references?

Lets say I have some code like this

let ref = Database.database().reference()
let refTwo = Database.database().reference()

 func getPosts() {
    ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { snap in 
     // get some posts
    })
  }

func getOtherStuff() {
    refTwo.child("child").queryOrderedByKey().observeSingleEvent(of: .value, with: { snap in 
     // get some other data
    })
    refTwo.removeAllObservers()
  }

And I call getPosts() and getOtherStuff() in viewDidLoad() do I need to use two different references or can I just use one ref for all of my queries?

I know if you have the same ref using .observe in two different locations the data is only returned once. So you wouldn't want to re-use that ref? However, here I am just using .observeSingleEvent so I'm not sure. Additionally, would it matter if they were on the same child?

Upvotes: 0

Views: 1760

Answers (2)

badjuicy
badjuicy

Reputation: 51

in Firebase 4.4 you need just use

var ref = Database.database().reference()

also you can see "Read and Write Data" in left list for basic structs.

example:

self.ref.child("users").child(user!.uid).setValue(["mentionName": ""])
self.ref.child("users").child(user!.uid).child("email").setValue(self.emailField.text)

reference: https://firebase.google.com/docs/database/ios/start

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598775

Firebase database references are just lightweight references to locations in the database. Nothing happens until you either attach a listener or write to them.

There is no need to use separate listeners in the scenario you shared. I would remove the call to removeAllObservers: since you're calling observeSingleEvent, the observers are automatically removed after the first time they fire.

Upvotes: 1

Related Questions