Laurent Maquet
Laurent Maquet

Reputation: 400

How to pipeline several request to Firebase in order to fetch data from multiple nodes at the same time

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.

JavaScript

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 :

Swift

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)

Upvotes: 5

Views: 1104

Answers (1)

Chris Edgington
Chris Edgington

Reputation: 3236

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 
}) 

Upvotes: 7

Related Questions