1

I'm having trouble with the below pattern. I need to synchronously wait for an initial async request, where the completion block in turn calls a list of async calls where each of the async calls need to wait for the previous one to end before it can start.

The below code would call all of the nested requests at once, which is not what I want.

let semaphore = DispatchSemaphore.init(value: 0)
self.getThings { (things) -> (Void) in
    for thing in things {
        self.getSomething { (somevalue) -> (Void) in
        }
    }
    semaphore.signal()
}
semaphore.wait()

So, what I've tried, is to add another semaphore inside the for loop but this has the effect that the nested request are never carried out - it waits indefinitely for semaphore2 signal which never happens. How do I fix this?

let semaphore = DispatchSemaphore.init(value: 0)
self.getThings { (things) -> (Void) in
    for thing in things {
        let semaphore2 = DispatchSemaphore.init(value: 0)
        self.getSomething { (somevalue) -> (Void) in
            semaphore2.signal()
        }
        semaphore2.wait()
    }
    semaphore.signal()
}
semaphore.wait()
Jonny
  • 15,955
  • 18
  • 111
  • 232
  • What about encapsulating things in `NSOperation`s that are executed in serial (by setting `NSOperationQueue`'s maximum operation count to `1`)? – meaning-matters Apr 23 '19 at 09:20
  • @meaning-matters if `getSomething`'s completion block is escaping, wouldn't `NSOperation` finish before the block is executed? – kubrick G Apr 23 '19 at 10:00

0 Answers0