Reputation: 13335
I am trying to use dispatch group as suggested here https://stackoverflow.com/a/35906703/406322
However, it seems like myGroup.notify is being called before all the iterations of the for loop is completed. What am I doing wrong?
let myGroup = DispatchGroup()
for channel in channels.subscribedChannels() {
myGroup.enter()
buildUser(channel) { (success, user) in
if success {
addUser(user)
}
print("Finished request \(user.id)")
myGroup.leave()
}
}
myGroup.notify(queue: .main) {
print("Finished all requests.")
}
The output is this:
Finished request 1
Finished all requests.
Finished request 2
Upvotes: 0
Views: 887
Reputation: 385
Not sure, but isn't your print("Finished request \(user.id)")
being called from a thread and therefore can be called after your print("Finished all requests.")
since it's on a main priority queue ?
try replacing
print("Finished request \(user.id)")
by:
DispatchQueue.main.async {
print("Finished request \(user.id)")
}
Testing it out in a playground works fine:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
class User {
var id: Int
init(id: Int) {
self.id = id
}
}
class Channel {
var user: User
init(user: User) {
self.user = user
}
}
var subscribedChannels: [Channel] = []
let user1 = User(id: 1)
let user2 = User(id: 2)
subscribedChannels.append(Channel(user: user1))
subscribedChannels.append(Channel(user: user2))
let myGroup = DispatchGroup()
let bgQueue = DispatchQueue.global(qos: .background)
func doSomething(channel: Channel, callback: @escaping (Bool, User) -> Void) {
print("called for \(channel.user.id)")
bgQueue.asyncAfter(deadline: .now() + 1) {
callback(true, channel.user)
}
}
for channel in subscribedChannels {
myGroup.enter()
doSomething(channel: channel) { (success, user) in
if success {
//
}
print("Finished request \(user.id)")
myGroup.leave()
}
}
myGroup.notify(queue: .main) {
print("Finished all requests.")
}
this prints
called for 1
called for 2
then 1 second later
Finished request 1
Finished request 2
Finished all requests.
I don't know your classes and methods so it's hard for me to know more
Upvotes: 2