初始化器
init(_:
init(_:bufferingPolicy:_:)
使用指定的缓冲策略和element-producing 闭包为元素类型构造异步流。
声明
init(
_ elementType: Element.Type = Element.self,
bufferingPolicy limit: AsyncThrowingStream<Element, Failure>.Continuation.BufferingPolicy = .unbounded,
_ build: (AsyncThrowingStream<Element, Failure>.Continuation) -> Void
) where Failure == Error
参数
elementType
AsyncThrowingStream
生成的元素类型。limit
缓冲区中保存的最大元素数。默认情况下,此值是无限的。使用
Continuation.BufferingPolicy
缓冲指定数量的最旧或最新元素。build
为
AsyncThrowingStream
生成值的自定义闭包。这个闭包接收一个AsyncThrowingStream.Continuation
实例,它用于向流提供元素并在完成时终止流。
详述
build
闭包收到的 AsyncStream.Continuation
适用于并发上下文。发送和完成是线程安全的;所有对延续的调用都被序列化。但是,从多个并发上下文调用它可能会导致 out-of-order 传递。
以下示例显示了使用此初始化程序创建的 AsyncStream
,该初始化程序在 one-second 间隔上生成 100 个随机数,调用 yield(_:)
将每个元素传递到等待调用点。当 for
循环退出时,流通过调用延续的 finish()
方法结束。如果随机数可被 5 整除且没有余数,则流将抛出 MyRandomNumberError
。
let stream = AsyncThrowingStream<Int, Error>(Int.self,
bufferingPolicy: .bufferingNewest(5)) { continuation in
Task.detached {
for _ in 0..<100 {
await Task.sleep(1 * 1_000_000_000)
let random = Int.random(in: 1...10)
if (random % 5 == 0) {
continuation.finish(throwing: MyRandomNumberError())
return
} else {
continuation.yield(random)
}
}
continuation.finish()
}
}
// Call point:
do {
for try await random in stream {
print ("\(random)")
}
} catch {
print ("\(error)")
}
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相关用法
- Swift AsyncThrowingStream init(unfolding:)用法及代码示例
- Swift AsyncThrowingStream filter(_:)用法及代码示例
- Swift AsyncThrowingStream max(by:)用法及代码示例
- Swift AsyncThrowingStream contains(where:)用法及代码示例
- Swift AsyncThrowingStream map(_:)用法及代码示例
- Swift AsyncThrowingStream prefix(_:)用法及代码示例
- Swift AsyncThrowingStream min(by:)用法及代码示例
- Swift AsyncThrowingStream allSatisfy(_:)用法及代码示例
- Swift AsyncThrowingStream contains(_:)用法及代码示例
- Swift AsyncThrowingStream compactMap(_:)用法及代码示例
- Swift AsyncThrowingStream reduce(_:_:)用法及代码示例
- Swift AsyncThrowingStream first(where:)用法及代码示例
- Swift AsyncThrowingStream drop(while:)用法及代码示例
- Swift AsyncThrowingStream flatMap(_:)用法及代码示例
- Swift AsyncThrowingStream min()用法及代码示例
- Swift AsyncThrowingStream prefix(while:)用法及代码示例
- Swift AsyncThrowingStream max()用法及代码示例
- Swift AsyncThrowingStream dropFirst(_:)用法及代码示例
- Swift AsyncThrowingStream用法及代码示例
- Swift AsyncThrowingFlatMapSequence min()用法及代码示例
- Swift AsyncThrowingMapSequence reduce(_:_:)用法及代码示例
- Swift AsyncThrowingPrefixWhileSequence drop(while:)用法及代码示例
- Swift AsyncThrowingMapSequence contains(_:)用法及代码示例
- Swift AsyncThrowingPrefixWhileSequence filter(_:)用法及代码示例
- Swift AsyncThrowingDropWhileSequence first(where:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 AsyncThrowingStream init(_:bufferingPolicy:_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。