I need to retrieve data from 4 nodes in my Firebase Database. By design, in firebase, this can only be done by firing 4 queries. In my case, those 4 queries are independent as I already know the path of each: I could fire them all at the same time.
I have learned from Frank van Puffelen that Firebase is able to pipeline several queries inside the same connection (see here).
This is very useful as it avoids to trigger sequentially n queries and to loose round-trip time.
In Javascript, we can do this wrapping the queries into an array of promises, and by firing them all together.
const arrayOfPromises = [
promise1,
promise2,
promise3,
promise4];
Promise.all(arrayOfPromises);
My question is how to proceed in Swift ?
I have tried to make an array of DatabaseReference
and to observe childValues from it :
let refs = [Database.database().reference().child("node1"),
Database.database().reference().child("node2"),
Database.database().reference().child("node3"),
Database.database().reference().child("node4")]
refs.child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
//Do something
}
But it seems that observeSingleEvent can only be fired from a single DatabaseReference (and not from an array of DatabaseReference)
A simultaneous connection is equivalent to one mobile device, browser tab, or server app connected to the database. This isn't the same as the total number of users of your app, because your users don't all connect at once.
10 for single-document requests and query requests. 20 for multi-document reads, transactions, and batched writes. The previous limit of 10 also applies to each operation.
Asynchronous listeners: Data stored in a Firebase Realtime Database is retrieved by attaching an asynchronous listener to a database reference. The listener is triggered once for the initial state of the data and again anytime the data changes. An event listener may receive several different types of events.
Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.
Probably the best way to do this in Swift would be to use DispatchGroups -
var nodes: [String] = ["node1", "node2", "node3", "node4"]
let dispatchGroup = DispatchGroup()
for node in nodes {
dispatchGroup.enter()
Database.database().reference().child(node).child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
//Do something
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main, execute: {
//Called when all requests have been fulfilled
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With