Skip to content

Instantly share code, notes, and snippets.

@mackoj
Created October 4, 2022 09:09
Show Gist options
  • Save mackoj/abf0a3dbceed1c3e808b3317abf01267 to your computer and use it in GitHub Desktop.
Save mackoj/abf0a3dbceed1c3e808b3317abf01267 to your computer and use it in GitHub Desktop.
This convert your Combine base code to Async/Await
import Fopundation
import Combine
extension AnyPublisher {
func async<NewOutput>(_ transform: @escaping (Output) throws -> NewOutput) async throws -> NewOutput {
try await withCheckedThrowingContinuation { continuation in
var cancellable: AnyCancellable?
cancellable = first()
.sink { result in
switch result {
case .finished:
break
case let .failure(error):
continuation.resume(throwing: error)
}
cancellable?.cancel()
} receiveValue: { value in
do {
let output = try transform(value)
continuation.resume(with: .success(output))
} catch {
continuation.resume(throwing: error)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment