Jim*_*mmy 2 ios firebase swift firebase-realtime-database
我正在使用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());
});
});
Run Code Online (Sandbox Code Playgroud)
我如何知道所有Firebase observeSingleEvent都已执行,因此我可以在我的集合视图中重新加载数据.
编辑:
经过更多的研究,这看起来非常类似于这个问题.我可以使用dispatch_group或Bolts框架
编辑2:
感谢@appzYourLife的回答.我也能用它来解决它RxSwift.我只是用观察者包装Firebase调用并将它们保存在一个数组中然后调用
Observable.zip(observables, { _ in }).subscribe(onCompleted: {
self.contentView.collection.reloadData() // do something here
})
Run Code Online (Sandbox Code Playgroud)
Luc*_*tti 11
如果您希望在完成所有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")
}
})
Run Code Online (Sandbox Code Playgroud)
涉及4个主要说明.
首先,我们创建一个小组DispatchGroup().该值将跟踪待处理块的数量.
let group = DispatchGroup()
Run Code Online (Sandbox Code Playgroud)然后在开始新的异步调用之前,我们告诉组有一个新的挂起块.
group.enter()
Run Code Online (Sandbox Code Playgroud)在回调闭包内,我们告诉组一个块已完成其工作.
group.leave()
Run Code Online (Sandbox Code Playgroud)当进入组的块数变为零时,我们告诉块运行一个闭包.
group.notify(queue: .main) {
print("All callbacks are completed")
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
1495 次 |
| 最近记录: |