Concurrency & Asynchronous Programming in Swift

May 20 2025 · Swift 6, iOS 18, Xcode 16

Lesson 04: Using AsyncStream

Demo

Episode complete

Play next episode

Next

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

In this demo, you’ll update TheMet app to use an AsyncStream to update the UI and show the search results.

func fetchObjects(for queryTerm: String) -> AsyncStream<Object> {

  return AsyncStream { continuation in
    let task = Task {
      if let objectIDs = try await self.service.getObjectIDs(from: queryTerm) {

        for (index, objectID) in objectIDs.objectIDs.enumerated()
        where index < self.maxIndex {
          if let object = try await self.service.getObject(from: objectID) {
            continuation.yield(object)
          }
        }
      }
    }

    continuation.onTermination = { _ in
      print("Task is cancelled")
      task.cancel()
    }
  }
}
.task {
  do {
    for await object in store.fetchObjects(for: query) {
      objects.append(object)
    }
  }
}
fetchObjectsTask = Task {
  do {
    objects = []
    for await object in store.fetchObjects(for: query) {
      objects.append(object)
    }
  }
}
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion