Initializer

init(_:bufferingPolicy:_:)

Constructs an asynchronous stream for an element type, using the specified buffering policy and element-producing closure.

Declaration 宣言

init(_ elementType: Element.Type = Element.self, bufferingPolicy limit: AsyncThrowingStream<Element, Failure>.Continuation.BufferingPolicy = .unbounded, _ build: (AsyncThrowingStream<Element, Failure>.Continuation) -> Void) where Failure == Error

Parameters パラメータ

elementType

The type of element the AsyncThrowingStream produces.

limit

The maximum number of elements to hold in the buffer. By default, this value is unlimited. Use a Continuation.BufferingPolicy to buffer a specified number of oldest or newest elements.

build

A custom closure that yields values to the AsyncThrowingStream. This closure receives an AsyncThrowingStream.Continuation instance that it uses to provide elements to the stream and terminate the stream when finished.

Discussion 解説

The AsyncStream.Continuation received by the build closure is appopriate for use in concurrent contexts. It is thread safe to send and finish; all calls are to the continuation are serialized. However, calling this from multiple concurrent contexts could result in out-of-order delivery.

The following example shows an AsyncStream created with this initializer that produces 100 random numbers on a one-second interval, calling yield(_:) to deliver each element to the awaiting call point. When the for loop exits and the stream finishes by calling the continuation’s finish() method. If the random number is divisble by 5 with no remainder, the stream throws a 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)")
}

See Also 参照

Creating a Continuation-Based Stream