Created
October 4, 2022 09:09
-
-
Save mackoj/abf0a3dbceed1c3e808b3317abf01267 to your computer and use it in GitHub Desktop.
This convert your Combine base code to Async/Await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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