Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch Group not working for completion block

Trying to get return reply objects from a network call. The session is a class that is using the star scream API. I just can't seem to get this to work. It's only printing out 1 set of results which is the from the first id. What am I missing here?

let myGroup = DispatchGroup()

for i in 0 ..< marketIds.count {
    myGroup.enter()
    self.session.retrieve(withMethod: MarketKeys.key, withParameters: [MarketKeys.id: marketIds[i]], completion: { (results, error) in
        print("results \n")
        print(results!)
        myGroup.leave()
        })
    }
myGroup.notify(queue:.main) {
print("Done")
}
like image 972
Russell Warwick Avatar asked Oct 16 '25 11:10

Russell Warwick


1 Answers

This article gives you a quick reference guide to simple DispatchGroup use.

An example:

let dispatchGroup = DispatchGroup()

dispatchGroup.enter()
longRunningFunction { dispatchGroup.leave() }

dispatchGroup.enter()
longRunningFunctionTwo { dispatchGroup.leave() }

dispatchGroup.notify(queue: .main) {
    print("Both functions complete 👍")
}

The notify function is called when all items in the queue have been processed and allows you to react to this accordingly. So the example above will run two long running tasks and then will output "Both functions complete 👍"

like image 160
Scriptable Avatar answered Oct 19 '25 02:10

Scriptable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!