AsyncSequence
概要
利用側
for-awai-in シンタックスを利用して記述できる。break や continue も同期的な for-in シンタックスと同様に利用できる。
code:swift
for await quake in quakes {
if quake.location == nil {
break
}
if quake.depth > 5 {
continue
}
// do something
}
code:swift
do {
for try await quake in quakeDownload {
// ...
}
} catch {
// ...
}
code:swift
Task {
for await quake in quakes {
// ...
}
}
無限に続いてしまう可能性がある場合は、キャンセルできるようにしておくこともできる。
code:swift
let iteration = Task {
for await quake in quakes {
// ...
}
}
// ...
iteration.cancel()
API 例
code:swift
// FileHandle からバイト列を非同期に読み込む
//
// public var bytes: AsyncBytes
for try await line in FileHandle.standardInput.bytes.lines { /* ... */ }
// URL から行を非同期に読み込む
//
// public var linets: AsyncLineSequence<AsyncBytes>
let url = URL(fileURLWithPath: "/tmp/somefile.txt")
for try await line in url.lines { /* ... */ }
// URLSession からバイト列を読み込む
//
// func bytes(from: URL) async throws -> (AsyncBytes, URLResponse)
let (bytes, response) = try await URLSession.shared.bytes(from: url)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throws MyNetworkingError.inavlidServerResponse
}
for try await byte in bytes { /* ... */ }
// 通知を待機する
//
// public func notifications(name: Notification.Name, object: AnyObject) -> Notifications
let center = NotificationCenter.default
let notification = await center.notifications(named: .NSPersistentStoreRemoteChange).first {
}
提供側
code:swift
class QuakeMonitor {
var quakeHandler: (Quake) -> Void
func startMonitoring()
func stopMonitoring()
}
let monitor = QuakeMonitor()
monitor.quakeHandler = { quake in
// ...
}
monitor.startMonitoring()
// ...
monitor.stopMonitoring()
code:swift
let quakes = AsyncStream(Quake.self) { continuation in
let monitor = QuakeMonitor()
monitor.quakeHandler = { quake in
continuation.yield(quake)
}
monitor.onTermination = { _ in
monitor.stopMonitoring()
}
monitor.startMonitoring()
}
参考