1

I'm using Firebase to store user info, and I have this nested function that fetch the post info, and then using the UID in post to fetch the user info.

Nested function to fetch post info and then fetch user

func fetchUser(completion: @escaping (User) -> Void) {
    REF_POST.queryOrdered(byChild: "timestamp").observe(.childAdded, with: { (postData) in
        let post = ConvertPost(data: postData.key)

        print(post.uid) >>>>>>UID ordered by timestamp<<<<<<<<

        REF_USER.child(post.uid).observeSingleEvent(of: .value, with: { (userData) in

            print(post.uid) >>>>>>UID order becomes different<<<<<<<<

            let user = ConvertUser(data: userData)
            completion(user)
    })

}

I have a print(uid) before observing the users, the output is ordered by timestamp, which is what I want:

PXT6********  
WT7i********    
WT7i********    
PXT6********  

And a print(uid) inside observing users, the output order is different:

WT7i********    
WT7i********    
PXT6********    
PXT6********   

so my question is why the order becomes different?
I'm calling the method in ViewDidLoad()
Is it something to do with the closure block?

Question Update

After some testing, I found that the output will always group the same uid together, something like A,A,B,B,C,C. Please help me.

Zehua Lin
  • 11
  • 2

1 Answers1

0

Use this code below:

func observeUsers(uid: String, completion:  @escaping (User) -> Void) {
    print(uid)
    REF_USERS.keepSynced(true) // <-- this will make sure your code will update with fresh data
    REF_USERS.child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
        print(uid)

        let user = ConvertUser(data: snapshot.value)
        completion(user)
        }
    })
}

Either use that code, or disable data persistance in your appDelegate. More information:Firebase : What is the difference between setPersistenceEnabled and keepSynced? and in the docs of Firebase ofcourse.

J. Doe
  • 12,159
  • 9
  • 60
  • 114
  • Thanks for the reply, I just tried your code by adding keepSynced(true) and the print output inside the block now becomes PXT6******** PXT6******** WT7i******** WT7i******** – Zehua Lin Jun 19 '17 at 12:47
  • Whats the order in Firebase? – J. Doe Jun 19 '17 at 12:59
  • in Firebase PXT6***** comes before WT7i******, but I don't think that's the problem.... the uid I pass in is in a certain order, and I want the output(which is the snapshot) to be in the same order. – Zehua Lin Jun 19 '17 at 13:12