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

风流意气都作罢 提交于 2020-01-13 10:58:29

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/48689441/how-to-pipeline-several-request-to-firebase-in-order-to-fetch-data-from-multiple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!