[英]Can I distinguish `DispatchGroup` async tasks completion?
Suppose I have three async functions A, B, C.假设我有三个异步函数 A、B、C。
I want a callback after completion of these three, I will use DispatchGroup
.我想在完成这三个后回调,我将使用
DispatchGroup
。
But I have a batch of these async tasks A, B, C.但我有一批这些异步任务 A、B、C。 Suppose, 6 of them.
假设,其中 6 个。
Now I want a callback after each of these A, B, C async task completion.现在我想要在每个 A、B、C 异步任务完成后进行回调。
Like,喜欢,
A
B
C
Callback
A
B
C
Callback
A
B
C
Callback
Using DispatchGroup
, I am getting,使用
DispatchGroup
,我得到,
A
B
C
A
B
C
A
B
C
Callback
as group,notify()
works only when everyone have group.leave()
.作为
group,notify()
仅在每个人都有group.leave()
。
Sample,样本,
// Called 6 times
private func fetchLists(in room: Room,
completion: @escaping( _ ownerList: [Any],
_ memberList: [Any],
_ subscribersList: [Any]) -> Void) {
var ownerList = [Any]()
var memberList = [Any]()
var subscribersList = [Any]()
let group = DispatchGroup()
group.enter()
// Asyncronous
fetchOwners(in: room, completion: { list in
ownerList = list
group.leave()
})
group.enter()
// Asyncronous
fetchMembers(in: room, completion: { list in
memberList = list
group.leave()
})
group.enter()
// Asyncronous
fetchSubscribers(in: room, completion: { list in
subscribersList = list
group.leave()
})
debug("Called 6 times")
group.notify(queue: .main) {
debug("Called 1 time. Want it to be called 6 times each with 3 batch.")
completion(memberList, ownerList, subscribersList)
}
}
As per DispatchGroup
's documentation the notify method is called when group is empty, which means you have to call group.leave()
as many times as you have called group.enter()
.根据
DispatchGroup
的文档,当 group 为空时调用 notify 方法,这意味着您必须调用group.enter()
() 与调用group.leave()
一样多次。 For your scenario, since you want to notify group each time a batch operation completes you have to use a separate group for each batch of tasks.对于您的方案,由于您希望在每次批处理操作完成时通知组,您必须为每批任务使用单独的组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.