How do I convert Combine publishers to async sequences in Swift?

In Swift, you can convert Combine publishers to asynchronous sequences using the `AsyncStream` or `AsyncThrowingStream`. This is especially useful when you want to integrate Combine's reactive programming capabilities with Swift's structured concurrency.

Keywords: Combine, AsyncSequence, Swift, reactive programming, Combine publishers
Description: Learn how to convert Combine publishers into async sequences in Swift, allowing for seamless integration of asynchronous programming with reactive streams.
        import Combine
        import Foundation

        // Sample Combine publisher
        let publisher = Just("Hello, AsyncSequence!")
            .eraseToAnyPublisher()

        // Convert Combine publisher to AsyncSequence
        func asyncSequenceFromPublisher(_ publisher: AnyPublisher) -> AsyncThrowingStream {
            AsyncThrowingStream { continuation in
                let cancellable = publisher.sink(
                    receiveCompletion: { completion in
                        switch completion {
                        case .finished:
                            continuation.finish()
                        case .failure(let error):
                            continuation.finish(throwing: error)
                        }
                    },
                    receiveValue: { value in
                        continuation.yield(value)
                    })
                
                // Store the cancellable if needed
                continuation.onTermination = { _ in
                    cancellable.cancel()
                }
            }
        }

        // Usage
        Task {
            let asyncSequence = asyncSequenceFromPublisher(publisher)
            for try await value in asyncSequence {
                print(value) // Output: Hello, AsyncSequence!
            }
        }
        

Keywords: Combine AsyncSequence Swift reactive programming Combine publishers