0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.