Why `AsyncStream` breaks structured concurrency?

Another option could be to set the continuation.onTermination closure, which will run immediately when the parent Task is cancelled. So in this example, you could use

func makeStream() -> AsyncStream<Int> {
    return AsyncStream { continuation in
        let task = Task {
            var n = 0
            while !Task.isCancelled {
                print("Sending", n)
                continuation.yield(n)
                try? await Task.sleep(nanoseconds: 1_000_000_000)
                n += 1
            }
            print("Cancelled!")
        }

        continuation.onTermination = { _ in
            task.cancel()
        }
    }
}

22 Likes