Modern Concurrency: Getting Started

Oct 18 2022 · Swift 5.5, iOS 15, Xcode 13.4

Part 1: Asynchronous Code

05. Using AsyncSequence in Views

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: 04. Asynchronous Sequences Next episode: 06. Additional Error Handling

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've reached locked video content where the transcript will be shown as obfuscated text.

Refresh your browser to make sure the course server is running or restart the server in Terminal.

Async sequence

In episode 3, you used Swift concurrency to fetch this list of available stock symbols.

.padding
// TODO...
🟩
.task {
  do {
    try await model.startTicker(selectedSymbols)
  } catch {
    lastErrorMessage = error.localizedDescription
  }
}
let (stream, response) = try await liveURLSession.bytes(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else {
  throw "The server responded with an error."
}
for try await line in stream.lines {
  print(line)
}
for try await line in stream.lines {
  print(line)
🟩
let sortedSymbols = try JSONDecoder()
  .decode([Stock].self, from: Data(line.utf8))
  .sorted(by: { $0.name < $1.name })
tickerSymbols = sortedSymbols
🟥
}

Update UI on main thread

It works! But there are warnings interspersed and also purple warnings next to tickerSymbols = [] and tickerSymbols = sortedSymbols.

await MainActor.run {
  tickerSymbols = []
}
await MainActor.run {
  tickerSymbols = sortedSymbols
}
await MainActor.run {
  tickerSymbols = sortedSymbols
  🟩print("Updated: \(Date())")🟥
}

Task hierarchy

First, a word about structured concurrency: click back to TickerView.

Handle cancellation errors

Keep an eye on the Xcode console while you tap the Back button.

} catch {
🟩
  if let error = error as? URLError, 
    error.code == .cancelled {
    return
  }
🟥
  lastErrorMessage = error.localizedDescription
}