<!--
{
  "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/AsyncThrowingStream",
  "metadataVersion" : "0.1.0",
  "role" : "Structure",
  "symbol" : {
    "kind" : "Structure",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Scs"
  },
  "title" : "AsyncThrowingStream"
}
-->

# AsyncThrowingStream

An asynchronous sequence generated from an error-throwing closure that
calls a continuation to produce new elements.

```
struct AsyncThrowingStream<Element, Failure> where Failure : Error
```

## Overview

`AsyncThrowingStream` conforms to `AsyncSequence`, providing a convenient
way to create an asynchronous sequence without manually implementing an
asynchronous iterator. In particular, an asynchronous stream is well-suited
to adapt callback- or delegation-based APIs to participate with
`async`-`await`.

In contrast to `AsyncStream`, this type can throw an error from the awaited
`next()`, which terminates the stream with the thrown error.

You initialize an `AsyncThrowingStream` with a closure that receives an
`AsyncThrowingStream.Continuation`. Produce elements in this closure, then
provide them to the stream by calling the continuation’s `yield(_:)` method.
When there are no further elements to produce, call the continuation’s
`finish()` method. This causes the sequence iterator to produce a `nil`,
which terminates the sequence. If an error occurs, call the continuation’s
`finish(throwing:)` method, which causes the iterator’s `next()` method to
throw the error to the awaiting call point. The continuation is `Sendable`,
which permits calling it from concurrent contexts external to the iteration
of the `AsyncThrowingStream`.

An arbitrary source of elements can produce elements faster than they are
consumed by a caller iterating over them. Because of this, `AsyncThrowingStream`
defines a buffering behavior, allowing the stream to buffer a specific
number of oldest or newest elements. By default, the buffer limit is
`Int.max`, which means it’s unbounded.

### Adapting Existing Code to Use Streams

To adapt existing callback code to use `async`-`await`, use the callbacks
to provide values to the stream, by using the continuation’s `yield(_:)`
method.

Consider a hypothetical `QuakeMonitor` type that provides callers with
`Quake` instances every time it detects an earthquake. To receive callbacks,
callers set a custom closure as the value of the monitor’s
`quakeHandler` property, which the monitor calls back as necessary. Callers
can also set an `errorHandler` to receive asynchronous error notifications,
such as the monitor service suddenly becoming unavailable.

```
class QuakeMonitor {
    var quakeHandler: ((Quake) -> Void)?
    var errorHandler: ((Error) -> Void)?

    func startMonitoring() {…}
    func stopMonitoring() {…}
}
```

To adapt this to use `async`-`await`, extend the `QuakeMonitor` to add a
`quakes` property, of type `AsyncThrowingStream<Quake>`. In the getter for
this property, return an `AsyncThrowingStream`, whose `build` closure –
called at runtime to create the stream – uses the continuation to
perform the following steps:

1. Creates a `QuakeMonitor` instance.
2. Sets the monitor’s `quakeHandler` property to a closure that receives
   each `Quake` instance and forwards it to the stream by calling the
   continuation’s `yield(_:)` method.
3. Sets the monitor’s `errorHandler` property to a closure that receives
   any error from the monitor and forwards it to the stream by calling the
   continuation’s `finish(throwing:)` method. This causes the stream’s
   iterator to throw the error and terminate the stream.
4. Sets the continuation’s `onTermination` property to a closure that
   calls `stopMonitoring()` on the monitor.
5. Calls `startMonitoring` on the `QuakeMonitor`.

```
extension QuakeMonitor {

    static var throwingQuakes: AsyncThrowingStream<Quake, Error> {
        AsyncThrowingStream { continuation in
            let monitor = QuakeMonitor()
            monitor.quakeHandler = { quake in
                 continuation.yield(quake)
            }
            monitor.errorHandler = { error in
                continuation.finish(throwing: error)
            }
            continuation.onTermination = { @Sendable _ in
                monitor.stopMonitoring()
            }
            monitor.startMonitoring()
        }
    }
}
```

Because the stream is an `AsyncSequence`, the call point uses the
`for`-`await`-`in` syntax to process each `Quake` instance as produced by the stream:

```
do {
    for try await quake in quakeStream {
        print("Quake: \(quake.date)")
    }
    print("Stream done.")
} catch {
    print("Error: \(error)")
}
```

## Topics

### Creating a Continuation-Based Stream

[`init(_:bufferingPolicy:_:)`](/documentation/Swift/AsyncThrowingStream/init(_:bufferingPolicy:_:))

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

[`AsyncThrowingStream.Continuation.BufferingPolicy`](/documentation/Swift/AsyncThrowingStream/Continuation/BufferingPolicy)

A strategy that handles exhaustion of a buffer’s capacity.

[`AsyncThrowingStream.Continuation`](/documentation/Swift/AsyncThrowingStream/Continuation)

A mechanism to interface between synchronous code and an asynchronous
stream.

### Finding Elements

[`contains(_:)`](/documentation/Swift/AsyncThrowingStream/contains(_:))

Returns a Boolean value that indicates whether the asynchronous sequence
contains the given element.

[`contains(where:)`](/documentation/Swift/AsyncThrowingStream/contains(where:))

Returns a Boolean value that indicates whether the asynchronous sequence
contains an element that satisfies the given predicate.

[`allSatisfy(_:)`](/documentation/Swift/AsyncThrowingStream/allSatisfy(_:))

Returns a Boolean value that indicates whether all elements produced by the
asynchronous sequence satisfy the given predicate.

[`first(where:)`](/documentation/Swift/AsyncThrowingStream/first(where:))

Returns the first element of the sequence that satisfies the given
predicate.

[`min()`](/documentation/Swift/AsyncThrowingStream/min())

Returns the minimum element in an asynchronous sequence of comparable
elements.

[`min(by:)`](/documentation/Swift/AsyncThrowingStream/min(by:))

Returns the minimum element in the asynchronous sequence, using the given
predicate as the comparison between elements.

[`max()`](/documentation/Swift/AsyncThrowingStream/max())

Returns the maximum element in an asynchronous sequence of comparable
elements.

[`max(by:)`](/documentation/Swift/AsyncThrowingStream/max(by:))

Returns the maximum element in the asynchronous sequence, using the given
predicate as the comparison between elements.

### Selecting Elements

[`prefix(_:)`](/documentation/Swift/AsyncThrowingStream/prefix(_:))

Returns an asynchronous sequence, up to the specified maximum length,
containing the initial elements of the base asynchronous sequence.

[`prefix(while:)`](/documentation/Swift/AsyncThrowingStream/prefix(while:))

Returns an asynchronous sequence, containing the initial, consecutive
elements of the base sequence that satisfy the given predicate.

### Excluding Elements

[`dropFirst(_:)`](/documentation/Swift/AsyncThrowingStream/dropFirst(_:))

Omits a specified number of elements from the base asynchronous sequence,
then passes through all remaining elements.

[`drop(while:)`](/documentation/Swift/AsyncThrowingStream/drop(while:))

Omits elements from the base asynchronous sequence until a given closure
returns false, after which it passes through all remaining elements.

[`filter(_:)`](/documentation/Swift/AsyncThrowingStream/filter(_:))

Creates an asynchronous sequence that contains, in order, the elements of
the base sequence that satisfy the given predicate.

### Transforming a Sequence

[`map(_:)`](/documentation/Swift/AsyncThrowingStream/map(_:)-4a4ke)

Creates an asynchronous sequence that maps the given closure over the
asynchronous sequence’s elements.

[`map(_:)`](/documentation/Swift/AsyncThrowingStream/map(_:)-58nrj)

Creates an asynchronous sequence that maps the given error-throwing
closure over the asynchronous sequence’s elements.

[`compactMap(_:)`](/documentation/Swift/AsyncThrowingStream/compactMap(_:)-7mgih)

Creates an asynchronous sequence that maps the given closure over the
asynchronous sequence’s elements, omitting results that don’t return a
value.

[`compactMap(_:)`](/documentation/Swift/AsyncThrowingStream/compactMap(_:)-944nt)

Creates an asynchronous sequence that maps an error-throwing closure over
the base sequence’s elements, omitting results that don’t return a value.

[`flatMap(_:)`](/documentation/Swift/AsyncThrowingStream/flatMap(_:)-vhin)

Creates an asynchronous sequence that concatenates the results of calling
the given error-throwing transformation with each element of this
sequence.

[`reduce(_:_:)`](/documentation/Swift/AsyncThrowingStream/reduce(_:_:))

Returns the result of combining the elements of the asynchronous sequence
using the given closure.

[`reduce(into:_:)`](/documentation/Swift/AsyncThrowingStream/reduce(into:_:))

Returns the result of combining the elements of the asynchronous sequence
using the given closure, given a mutable initial value.

### Creating an Iterator

[`makeAsyncIterator()`](/documentation/Swift/AsyncThrowingStream/makeAsyncIterator())

Creates the asynchronous iterator that produces elements of this
asynchronous sequence.

[`AsyncThrowingStream.Iterator`](/documentation/Swift/AsyncThrowingStream/Iterator)

The asynchronous iterator for iterating an asynchronous stream.

### Supporting Types

[`AsyncThrowingStream.AsyncIterator`](/documentation/Swift/AsyncThrowingStream/AsyncIterator)

The type of asynchronous iterator that produces elements of this
asynchronous sequence.



---

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)