Last active
June 21, 2024 12:17
-
-
Save T1T4N/7fc3414c8c5629ef0335e44dd2fc0f10 to your computer and use it in GitHub Desktop.
A Swift Extension for converting a Combine Publisher 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
extension Publisher { | |
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *) | |
func asyncFirst() async throws -> Output? { | |
return try await self | |
.first() | |
.values | |
.first { _ in true } | |
} | |
// https://medium.com/geekculture/from-combine-to-async-await-c08bf1d15b77 | |
func asyncFirstManual() async throws -> Output? { | |
try await withCheckedThrowingContinuation { continuation in | |
var cancellable: AnyCancellable? | |
var finishedWithoutValue = true | |
cancellable = self | |
.first() | |
.sink { result in | |
switch result { | |
case .finished: | |
if finishedWithoutValue { | |
continuation.resume(with: .success(nil)) | |
} | |
case let .failure(error): | |
continuation.resume(throwing: error) | |
} | |
cancellable?.cancel() | |
} receiveValue: { value in | |
finishedWithoutValue = false | |
continuation.resume(with: .success(value)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment