<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/AsyncStream/init(unfolding:onCancel:)",
  "metadataVersion" : "0.1.0",
  "role" : "Initializer",
  "symbol" : {
    "kind" : "Initializer",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:ScS9unfolding8onCancelScSyxGxSgyYac_yycSgtcfc"
  },
  "title" : "init(unfolding:onCancel:)"
}
-->

# init(unfolding:onCancel:)

Constructs an asynchronous stream from a given element-producing
closure, with an optional closure to handle cancellation.

```
@preconcurrency init(unfolding produce: @escaping @Sendable () async -> Element?, onCancel: (@Sendable () -> Void)? = nil)
```

## Parameters

`produce`

A closure that asynchronously produces elements for the
stream.

`onCancel`

A closure to execute when canceling the stream’s task.

## Discussion

Use this convenience initializer when you have an asynchronous 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 `AsyncSequence` protocol automatically, including termination
(either by cancellation or by returning `nil` from the closure to finish
iteration).

The following example shows an `AsyncStream` 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.

```
let stream = AsyncStream<Int> {
    await Task.sleep(1 * 1_000_000_000)
    return Int.random(in: 1...10)
} onCancel: { @Sendable () in print("Canceled.") }

// Call point:
for await random in stream {
    print(random)
}
```

> Note: Because the system might call the `onCancel` callback as
> part of task cancellation, it’s subject to the same considerations for
> avoiding deadlock as outlined in the documentation for
> ``doc://com.apple.Swift/documentation/Swift/withTaskCancellationHandler(operation:onCancel:)``.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)