AsyncSequence 简介
AsyncSequence 是一个支持异步迭代的协议,它和 Sequence 非常类似,同样支持使用 for、while、repeat 循环访问子元素,也支持使用 map、filter、reduce 等高阶函数,只不过这些操作都是异步的。
URL 在 iOS 15.0 内置了一个属性 line ,它的定义如下:
1
|
var lines: AsyncLineSequence<URL.AsyncBytes> { get }
|
AsyncLineSequence 是泛型结构体:
1
|
struct AsyncLineSequence<Base> where Base : AsyncSequence, Base.Element == UInt8
|
我们在这里看到了 AsyncSequence 的身影,正是它赋予了 URL 异步获取数据的能力。我们来看看如下示例代码,它会逐行打印返回的内容:
1
2
3
4
5
6
7
8
|
func fetchLines() async throws {
let url = URL(string: "https://raw.githubusercontent.com/zzzwco/resources/main/eul/lovethree.txt")!
for try await line in url.lines {
print("###\n\(line)\n###\n")
}
}
try? await fetchLines()
|
在介绍 TaskGroup 时,我们就已经遇到过使用 for await 进行异步迭代了,这是循环遍历 AsyncSequence 的常用方式。上例中还使用了 try ,是因为从网络获取数据可能会失败并抛出错误。这里我们没有在内部处理错误,而是选择了向外传递错误。
和 Sequence 一样,异步序列也可以使用 makeAsyncIterator() 方法生成迭代器,然后不停地重复调用 next(),直到返回 nil 时循环结束。与 Sequence 不一样的是,这里的 next() 是使用 async 标记的异步方法,调用方需要使用 await 来标识等待单个异步结果的返回。
实际上,编译器会将上面的 for-try-await-in 转换成如下代码:
1
2
3
4
|
var iterator = url.lines.makeAsyncIterator()
while let line = try await iterator.next() {
print("###\n\(line)\n###\n")
}
|
我们也可以通过上面的代码获取迭代器,然后进行更多的操作,比如只获取第一行内容:
1
2
3
|
if let first = try await iterator.next() {
print("###\n\(first)\n###\n")
}
|
AsyncSequence 支持常用的选择、查找等操作,比如判断异步结果是否包含 “love”:
1
2
|
let hasLove = try await url.lines.contains{ $0.contains("love") }
printLog(hasLove)
|
还能进行各种转换操作,比如使用 reduce 方法拼接各个异步结果:
1
2
|
let res = try await url.lines.reduce("", +)
printLog(res)
|
对原有的异步序列进行转换操作时,会生成一个新的异步类型实例。比如下面的 stream 是经 map 操作后返回的 AsyncMapSequence 类型实例:
1
2
3
4
5
6
7
|
let stream = url.lines.map { v -> String in
printLog(v)
return "❤️\(v)❤️"
}
for try await v in stream {
printLog(v)
}
|
通过打印结果可以看出,每获取一行内容,stream 就进行一次转换操作。也就是说,异步序列的转换操作并不是等所有的结果返回之后才集中处理,这个操作是即时的。
我们试着将如下代码删除:
1
2
3
|
for try await v in stream { // -
printLog(v) // -
} // -
|
结果控制台并没有打印任何东西,由于转换操作只是将原来的异步序列转换成另一种特定类型的异步序列,本质上它们都是异步序列。因此我们可以得出一个结论:异步序列只是定义了获取数据的方式,它并不生产和存储任何数据,只有数据被请求时,它才会作出响应。
我们可以把异步序列想象成一个工厂,数据经过加工后然后返回。而转换操作就像把原来的工厂换成另一种特殊的工厂,但工厂的职责是一样的,只是返回的数据不一样。不管是什么工厂,它都不会自己生产数据。它是懒惰的,除非我们主动向它索要数据时,它才会向外部请求数据然后进行加工处理。它也是无私的,不会贪婪地存储数据,外部输入的数据经过加工后都会被送回给请求方。
自定义 AsyncSequence
系统内置的许多类型都已经默认支持 AsyncSequence,比如 TaskGroup、URLSession、Notification 等,我们可以很方便地调用相应的 API 来实现功能,但有时候我们要实现自己的异步序列来满足特定的需求场景。
要实现自定义异步序列,需要实现 AsyncSequence 协议,其定义如下:
1
2
3
4
5
6
7
8
|
protocol AsyncSequence {
associatedtype AsyncIterator : AsyncIteratorProtocol
associatedtype Element where Self.Element == Self.AsyncIterator.Element
func makeAsyncIterator() -> Self.AsyncIterator
}
|
要实现该协议,只需实现 makeAsyncIterator() 方法即可,该方法返回的是遵循 AsyncIteratorProtocol 的关联类型 AsyncIterator 实例。需要注意的是,另一个关联类型 Element 在这两个协议中需要保持类型一致。
AsyncIteratorProtocol 协议定义如下,实现 next() 方法即可实现该协议:
1
2
3
4
5
|
protocol AsyncIteratorProtocol {
associatedtype Element
mutating func next() async throws -> Self.Element?
}
|
了解了以上概念后,下面的示例就很好理解了。它实现的是给定一系列的底数和指数(以元组类型表示一对数据),对每对数据其进行指数计算,异步迭代返回幂值,这里我们使用 Task.sleep 将计算过程模拟成了耗时的异步事件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
struct Power: AsyncSequence {
typealias Element = CGFloat
let input: [(x: CGFloat, y: CGFloat)]
struct AsyncIterator: AsyncIteratorProtocol {
let input: [(x: CGFloat, y: CGFloat)]
var idx = 0
mutating func next() async -> Element? {
guard idx < input.count else { return nil }
defer { idx += 1 }
let v = input[idx]
// 模拟耗时的异步操作
let task = Task { () -> CGFloat in
try await Task.sleep(seconds: Double.random(in: 0...1))
return pow(v.x, v.y)
}
return try? await task.value
}
}
func makeAsyncIterator() -> AsyncIterator {
AsyncIterator(input: input)
}
}
let random = { CGFloat(Int.random(in: 1...$0)) }
let input = (0..<10).map { _ in (random(100), random(10)) }
printLog(input)
for await v in Power(input: input) {
printLog(v)
}
|