Philip Sopher
Philip Sopher

Reputation: 783

Firebase Queries Not Firing in Order that they were called

I'm calling Firebase queries inside a for loop. However, the Firebase queries aren't firing in the order that they're called. Here's the code:

NSLog(@"%@", self.orderedKeys.description);

for (NSInteger i = 0; i < self.orderedKeys.count; i++) {
        [[selectedLanguageRef childByAppendingPath:self.orderedKeys[i]] observeSingleEventOfType:FEventTypeValue withBlock:^(FDataSnapshot *userSnapshot) {             
            NSLog(@"%@", self.orderedKeys.description);
            NSLog(@"%@", userSnapshot.key);
        }];
}

In this code, the NSLog returns this for self.orderedKeys.description:

fakeUser8, fakeUser7, "facebook:10205598530457903", fakeUser3, fakeUser10, fakeUser9, fakeUser14, fakeUser13

But the NSLog for userSnapshot.key will always fire in this order:

fakeUser3, fakeUser10, facebook:10205598530457903, fakeUser8, fakeUser7, fakeUser14, fakeUser13, fakeUser9

What's going on here? How do I get the queries to fire in the same order that they're called?

Upvotes: 0

Views: 102

Answers (2)

Jay
Jay

Reputation: 35677

Firebase is asynchronous and your code may be overwriting returned values or the values may be returning in an unexpected order due to lag.

Say for example your first query fires and there's a delay returning that, but the second query returns the data faster. The returned data is not synchronous like code is so you need to deal with the returned data before moving on.

In general, Firebase needs to be structured in the way you are going to use it; pre-planning for queries, breaking out nodes that will be observed, denormalizing data, accounting for it's asynchronous nature as well as planning for rules is something that needs to be done up front.

Upvotes: 2

jsd
jsd

Reputation: 7703

I haven't used Firebase specifically but it seems like a problem with running multiple asynchronous calls at the same time. You could use a serial queue to ensure only one runs at a time.

https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW6

Upvotes: 0

Related Questions