# AsyncStream and Cancellation

**URL:** <https://forums.swift.org/t/asyncstream-and-cancellation/52562>\
**Category:** Using Swift\
**Created:** [October 3, 2021, 4:01am UTC](https://forums.swift.org/t/asyncstream-and-cancellation/52562 "2021-10-03T04:01:14Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![gwendal.roue](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/gwendal.roue/32/13992_2.png) [@gwendal.roue](https://forums.swift.org/u/gwendal.roue)\
**Post date:** [November 8, 2021, 6:48am UTC](https://forums.swift.org/t/asyncstream-and-cancellation/52562/7 "2021-11-08T06:48:01Z")

</div>

> [@Jon\_Shier](#):
>
> If you don't call `continuation.finish()` but you exit iteration early, the `AsyncStream` will terminate in the `cancelled` state, but only once the continuation has been deinitialized. I'm not sure about this as I haven't been able to specifically structure a test to confirm it. Alternatively, this behavior could be due to the lifetime of the iterator since the loop was broken early. But in my testing the termination handler isn't called until my use of the continuation has ended. This means infinite streams will never actually be cancelled by early loop exit, as far I can tell, but streams with a fixed number of elements will.

I produce infinite streams for GRDB (database observation never ends), so I'm very eager to test that task cancellation and early loop exit correctly release resources as soon as possible.

Speaking of early exit specifically, I had some success based on the (experimental) fact that the async runtime notifies this termination with the deinitialization of the _iterator_ (deinitialization of the continuation is not observable, so I ignore it). I thus make sure resources that should be released by the end of loop are only retained by the iterator ([there](https://github.com/groue/GRDB.swift/blob/861ca5f022463164ca1fd5808f4fb37060fbbe03/GRDB/ValueObservation/ValueObservation.swift#L271-L318)), and [tests](https://github.com/groue/GRDB.swift/blob/861ca5f022463164ca1fd5808f4fb37060fbbe03/Tests/GRDBTests/ValueObservationTests.swift#L597-L719) pass.

---

_[View the full topic](https://forums.swift.org/t/asyncstream-and-cancellation/52562)._
