DebounceAsyncSequence

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

A async sequence that emits elements only after a specified time interval elapses between emissions.

Use DebounceAsyncSequence async sequence to control the number of values and time between delivery of values from the base async sequence. This async sequence is useful to process bursty or high-volume async sequences where you need to reduce the number of elements emitted to a rate you specify.

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

for element in try await self.stream.debounce(for: 0.1) {
    print(element)
}

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

    Declaration

    Swift

    public typealias Element = T.Element

Initialization

  • Creates an async sequence that emits elements only after a specified time interval elapses between emissions.

    Declaration

    Swift

    public init(
        _ base: T,
        dueTime: TimeInterval
    )

    Parameters

    base

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

    dueTime

    The amount of time the async sequence should wait before emitting an element.

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.