Skip to content

AsyncStream(unfolding:onCancel:) onCancel block is called twice #83137

@BrentMifsud

Description

@BrentMifsud

Description

When cancelling an AsyncStream(unfolding:onCancel:), the onCancel block is executed twice.

Reproduction

let task = Task {
    let stream = AsyncStream {
        try? await Task.sleep(for: .seconds(1))
        return Int.random(in: 1...100)
    } onCancel: {
        print("Stream cancelled") // this prints twice
    }

    for await value in stream {
        print("Received value: \(value)")
    }
}

Task {
    try? await Task.sleep(for: .seconds(5))
    task.cancel()
}

also attached a playground that reproduces the issue:

AsyncStreamCancellation.playground.zip

Expected behavior

the onCancel block should only be called once

Environment

swift-driver version: 1.127.8 Apple Swift version 6.2 (swiftlang-6.2.0.13.10 clang-1700.3.13.4)
Target: arm64-apple-macosx15.0

Also happens in Xcode 26 beta 3, so the issue is not fixed on the current swift 6.2 beta toolchain.

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.triage neededThis issue needs more specific labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions