Swiftpack.co - petrpavlik/CombineToAsyncAwait as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by petrpavlik.
petrpavlik/CombineToAsyncAwait 0.2.0
Automatically convert Combine Publishers into Swift 5.5 async methods.
⭐️ 4
🕓 1 week ago
iOS macOS
.package(url: "https://github.com/petrpavlik/CombineToAsyncAwait.git", from: "0.2.0")

CombineToAsyncAwait

Automatically convert Combine Publishers into Swift 5.5 async methods.

Example

Let's convert a Combine publisher provided by Apple to make a network request into async/await

Combine implementation

URLSession.shared.dataTaskPublisher(for: url).sink { completion in
    // check error
} receiveValue: { value in
    // process value
}.store(in: &cancellables)

Async/await bridge

import CombineToAsyncAwait

extension URLSession {
    func data(for url: URL) async throws -> (Data, URLResponse) {
        try await self.dataTaskPublisher(for: url).asyncValue()
    }
}

final class NetworkingTests: XCTestCase {
    func testNetworkRequest() async {
        do {
            let (data, response) = try await URLSession.shared.data(for: URL(string: "https://google.com")!)
        } catch {

        }
    }
}

Note: Apple has actually introduced async/await versions of this as a part of foundation on iOS 15 and corresponding OSes, so this is only to demonstrate how easy it is to turn a Combine publisher into an async method.


Contributions and more features, such as support for async sequences will be added.

See this package and thousands of others on swiftpack.co

GitHub

link
Stars: 4
Last commit: 1 week ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.

Release Notes

0.2.0
1 week ago

Add support for AsyncStream and AsyncThrowingStream

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics