所有firebase呼叫完成后如何重新加载数据



我正在使用firebase(swift)读取用户属于的组ID列表,然后在ID上循环以获取有关组的更多信息。与此类似的东西(伪代码):

// List the names of all Mary's groups
var ref = new Firebase("https://docs-examples.firebaseio.com/web/org");
// fetch a list of Mary's groups
ref.child("users/mchen/groups").on('child_added', function(snapshot) {
  // for each group, fetch the name and print it
  String groupKey = snapshot.key();
  ref.child("groups/" + groupKey + "/name").once('value', function(snapshot) {
    System.out.println("Mary is a member of this group: " + snapshot.val());
  });
});

我如何知道所有Firebase observeSingleEvent都已经执行了,以便我可以在收集视图中重新加载数据。

编辑:

进行了更多的研究后,这看起来与这个问题非常相似。我可以使用dispatch_group或螺栓框架

编辑2:

感谢@appzyourlife的回答。我还能够使用RxSwift解决它。我只是用观察者包裹了壁炉呼叫,然后将它们保存在数组中,然后称为

Observable.zip(observables, { _ in }).subscribe(onCompleted: {
       self.contentView.collection.reloadData() // do something here
}) 

如果您想在所有firebase呼叫完成时都要通知,则可以使用此代码

let ref = FIRDatabase.database().reference()
ref.child("users/mchen/groups").observeSingleEvent(of: .value, with: { snapshot in
    let groupKeys = snapshot.children.flatMap { $0 as? FIRDataSnapshot }.map { $0.key }
    // This group will keep track of the number of blocks still pending 
    let group = DispatchGroup()
    for groupKey in groupKeys {
        group.enter()
        ref.child("groups").child(groupKey).child("name").observeSingleEvent(of: .value, with: { snapshot in
            print("Mary is a member of this group: (snapshot.value)")
            group.leave()
        })
    }
    // We ask to be notified when every block left the group
    group.notify(queue: .main) {
        print("All callbacks are completed")
    }
})

它如何工作?

涉及4个主要说明。

  1. 首先,我们创建一个组DispatchGroup()。此值将跟踪待处理块的数量。

    let group = DispatchGroup()
    
  2. 然后开始一个新的异步呼叫,我们告诉组有一个新的待处理块。

    group.enter()
    
  3. 在回调关闭中,我们告诉小组一个块已经完成了工作。

    group.leave()
    
  4. 我们告诉块时,当组中的块数确实变为

    group.notify(queue: .main) {
        print("All callbacks are completed")
    }
    

您有组列表,因此您可以将计数存储在一个int对象中。假设总计。

然后取另一个对象。假设计数器。

然后在每个完成处理程序中。印刷语句

之后
ref.child("groups/" + groupKey + "/name").once('value', function(snapshot) 
{
            System.out.println("Mary is a member of this group: " + snapshot.val());
            if counter == count
            {
                  collectionView.reload();
            }
            else
            {
                  counter += 1;
            }
});

最新更新