WWDC21-Concurrency-AsncSequence

1. for-await-in

1
for try await event in endpointURL.lines
  • 可以中断循环:break/continue

  • 可以和其他任务同步进行:

    • let iteration1 = async {
          for await quake in quakes { }
      }
      let iteration2 = async {
          do {
              for try await quake in quakeDownload { }
          } catch { }
      }
      <!--1-->
      

3. AsycnSequence APIs

  • FileHandle.standardInput.bytes.lines

  • URLSession.shared.bytes(from: url)

    • let (bytes, response) = try await URLSession.shared.bytes(from: url)
      guard let httpResponse = response as? HTTPURLResponse,
            httpResponse.statusCode == 200 /* OK */
      else {
          throw MyNetworkingError.invalidServerResponse
      }
      for try await byte in bytes {
          ...
      }
      <!--2-->
  • Other Operations: map、max、prefix、...

4. BuildYourOwn - AsyncStream

1
2
3
4
5
6
7
8
let quakes = AsyncStream(Quake.self) { continuation in
quakeHandlerFunc { quake in
continuation.yield(quake)
}
continuation.onTermination = { _ in
stopFunc()
}
}
0%