ThrottleAsyncSequence

public struct ThrottleAsyncSequence<T> : AsyncSequence where T : AsyncSequence
extension ThrottleAsyncSequence: AsyncIteratorProtocol

An async sequence that emits either the most-recent or first element emitted by the base async sequence in a specified time interval.

ThrottleAsyncSequence selectively emits elements from a base async sequence during an interval you specify. Other elements received within the throttling interval aren’t emitted.

let stream = AsyncStream<Int> { continuation in
    continuation.yield(0)
    try? await Task.sleep(nanoseconds: 100_000_000)
    continuation.yield(1)
    try? await Task.sleep(nanoseconds: 100_000_000)
    continuation.yield(2)
    continuation.yield(3)
    continuation.yield(4)
    continuation.yield(5)
    continuation.finish()
}

for element in try await self.stream.throttle(for: 0.05, latest: true) {
    print(element)
}

// Prints:
// 0
// 1
// 2
// 5
  • The kind of elements streamed.

    Declaration

    Swift

    public typealias Element = T.Element

Initialization

  • Creates an async sequence that emits either the most-recent or first element emitted by the base async sequence in a specified time interval.

    Declaration

    Swift

    public init(
        _ base: T,
        interval: TimeInterval,
        latest: Bool
    )

    Parameters

    base

    The async sequence in which this sequence receives it’s elements.

    interval

    The interval in which to emit the most recent element.

    latest

    A Boolean value indicating whether to emit the most recent element. If false, the async sequence emits the first element received during the interval.

AsyncSequence

  • Creates an async iterator that emits elements of this async sequence.

    Declaration

    Swift

    public func makeAsyncIterator() -> AsyncThrowingStream<Element, Error>.Iterator

    Return Value

    An instance that conforms to AsyncIteratorProtocol.

AsyncIteratorProtocol

  • next() Asynchronous

    Produces the next element in the sequence.

    Declaration

    Swift

    public mutating func next() async throws -> Element?

    Return Value

    The next element or nil if the end of the sequence is reached.