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