# “try-iterating” an \`AsyncStream\`

**URL:** <https://forums.swift.org/t/try-iterating-an-asyncstream/62642>\
**Category:** Using Swift\
**Created:** [January 18, 2023, 9:01pm UTC](https://forums.swift.org/t/try-iterating-an-asyncstream/62642 "2023-01-18T21:01:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![taylorswift](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/taylorswift/32/43413_2.png) [@taylorswift](https://forums.swift.org/u/taylorswift)\
**Post date:** [January 18, 2023, 9:01pm UTC](https://forums.swift.org/t/try-iterating-an-asyncstream/62642/1 "2023-01-18T21:01:03Z")

</div>

i want to use an `AsyncStream` to buffer some plain-old-data:

```swift
actor SessionPool
{
    private
    let egress:AsyncStream<SessionIdentifier>.Iterator
    nonisolated
    let ingress:AsyncStream<SessionIdentifier>.Continuation
}

```

the idea is the stream would ensure that if a `deinit` yields something to `SessionPool.ingress`, that `SessionIdentifier` should be available for the next consumer.

```swift
final
class Session
{
    deinit
    {
        self.pool.ingress.yield(self.id)
    }
}
@available(*, unavailable)
extension Session:Sendable
{
}

```

```swift
func useSessions(pool:SessionPool)
{
     // number of generated sessions should never exceed 1!
     do
     {
        let session:Session = await pool.next()
        // session.deinit()
     }
     do
     {
        let session:Session = await pool.next()
        // session.deinit()
     }
}

```

but the problem is now implementing `SessionPool.next()`.

```swift
extension SessionPool
{
    nonisolated
    func next() async -> Session
    {
        ...
    }
    private
    func next() -> SessionIdentifier
    {
        // ???
    }
}

```

rather than suspending if `self.egress` has no buffered session identifiers, `next()` should just generate a new one and return it. ideally with some kind of API like

```swift
extension SessionPool
{
    private
    func next() -> SessionIdentifier
    {
        self.egress.nextIfBuffered() ?? self.generateNewSessionIdentifier()
    }
}

```

is there any way to accomplish this?
