A closure that asynchronously produces elements for the stream.
Initializerinit(unfolding:
init(unfolding:onCancel:)
Constructs an asynchronous stream from a given element-producing closure, with an optional closure to handle cancellation.
Availability
- iOS 13.0+
- iPadOS 13.0+
- macOS 10.15+
- Mac Catalyst 15.0+
- tvOS 13.0+
- watchOS 6.0+
- Xcode 13.0+
Technology
- Swift Standard Library Swift標準ライブラリ
Declaration 宣言
init(unfolding produce: @escaping () async -> Element?, onCancel: (@Sendable () -> Void
)? = nil)
Parameters パラメータ
produce
onCancel
A closure to execute when canceling the stream’s task.
Discussion 解説
Use this convenience initializer when you have an asychronous function that can produce elements for the stream, and don’t want to invoke a continuation manually. This initializer “unfolds” your closure into an asynchronous stream. The created stream handles conformance to the Async
protocol automatically, including termination (either by cancellation or by returning nil
from the closure to finish iteration).
The following example shows an Async
created with this initializer that produces random numbers on a one-second interval. This example uses the Swift multiple trailing closure syntax, which omits the unfolding
parameter label.