# Why \`AsyncStream\` breaks structured concurrency?

**URL:** <https://forums.swift.org/t/why-asyncstream-breaks-structured-concurrency/71477>\
**Category:** Using Swift\
**Created:** [April 26, 2024, 3:34am UTC](https://forums.swift.org/t/why-asyncstream-breaks-structured-concurrency/71477 "2024-04-26T03:34:01Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![Wouter01](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wouter01/32/35087_2.png) [@Wouter01](https://forums.swift.org/u/Wouter01)\
**Post date:** [April 26, 2024, 11:10am UTC](https://forums.swift.org/t/why-asyncstream-breaks-structured-concurrency/71477/4 "2024-04-26T11:10:35Z")

</div>

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

```swift
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()
        }
    }
}

```

---

_[View the full topic](https://forums.swift.org/t/why-asyncstream-breaks-structured-concurrency/71477)._
