“Unlike other continuations in Swift, AsyncStream.Continuation supports escaping.”

I didn't really understand exactly what @John_McCall meant above. I think he is saying that this is an expected use pattern:

// Is this an expected and acceptable use pattern?
    private var continuation: AsyncStream<String>.Continuation?

    lazy var outputStream = AsyncStream<String> { continuation in
        self.continuation = continuation
    }
    
    private func pushValue() {
        continuation?.yield("My String")
    }

Afaict this works and doesn't appear to be broken in any way, but it feels a little strange to me. If this is "not the right way", please let me know :slight_smile:

Also note that, in the example above, the stream is intended to always be "open", and so you never need to finish the continuation.

Edit: Nevermind, read through SE-0314 (Second review): AsyncStream and AsyncThrowingStream - #37 by yuriferretti, where it was confirmed that storing the continuation outside the closure is expected and fine.

Also found @taylorswift's other thread: `AsyncStream` constructor which also returns its Continuation

I agree that it is a rather awkward pattern, I would be in favor of either a constructor that returns the continuation too, or another primitive that is better suited for this scenario :slight_smile:

1 Like