Created
April 7, 2022 13:12
-
-
Save Edudjr/be5ebe85a7ebc0c114aaeb7c5e3c3dd1 to your computer and use it in GitHub Desktop.
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
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