Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Edudjr/be5ebe85a7ebc0c114aaeb7c5e3c3dd1 to your computer and use it in GitHub Desktop.
Save Edudjr/be5ebe85a7ebc0c114aaeb7c5e3c3dd1 to your computer and use it in GitHub Desktop.
enum AsyncError: Error {
case finishedWithoutValue
}
extension AnyPublisher {
func async() async throws -> Output {
try await withCheckedThrowingContinuation { continuation in
var cancellable: AnyCancellable?
var finishedWithoutValue = true
cancellable = first()
.sink { result in
switch result {
case .finished:
if finishedWithoutValue {
continuation.resume(throwing: AsyncError.finishedWithoutValue)
}
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