Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tonyarnold/749912b8c541cef4e2e6d6ce2c898628 to your computer and use it in GitHub Desktop.
Save tonyarnold/749912b8c541cef4e2e6d6ce2c898628 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