iOS Concurrency with GCD & Operations

Sep 12 2023 · Swift 5.8, macOS 13, iOS 16, Xcode 14.3

Part 1: Grand Central Dispatch

08. Wrap an Asynchronous Function

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 07. Use a Group of Tasks Next episode: 09. Challenge: Download a Group of Images

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

What if you need to call an asynchronous function as part of the group? How can you tell the group when it really finishes?

func asyncAdd(
  _ input: (Int, Int),
  runQueue: DispatchQueue = DispatchQueue.global(qos: .userInitiated),
  completionQueue: DispatchQueue = DispatchQueue.main,
  completion: @escaping (Result<Int, SlowAddError>) -> ()) {
  runQueue.async {
    let result = slowAddPlus(input)
    completionQueue.async { completion(result) }
  }
}
func asyncAdd_Group(
  _ input: (Int, Int),
  runQueue: DispatchQueue = DispatchQueue.global(qos: .userInitiated),
  completionQueue: DispatchQueue = DispatchQueue.main,
  group: DispatchGroup,
  completion: @escaping (Result<Int, SlowAddError>) -> ()) {
}
asyncAdd(input) { result in
  completionQueue.async { completion(result) }
}
group.enter()
defer { group.leave() }  // add this line
completionQueue.async { completion(result) }  // already written
for pair in numberArray {
  asyncAdd_Group(pair, group: wrappedGroup) { result in  // provide completion argument
    print("Result = \(result)")
  }
}
wrappedGroup.notify(queue: DispatchQueue.main) {
  print("WRAPPED ASYNC ADD: Completed all tasks")
  sleep(1)
  PlaygroundPage.current.finishExecution()
}
=== Group of async tasks ===

Result = success(9)
Result = success(1)
Result = success(5)
Result = success(17)
Result = failure(WrapAsyncMethod_Sources.SlowAddError.notEnoughFingers)
WRAPPED ASYNC ADD: Completed all tasks