初始化器
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:_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。