Forked from Edudjr/migrate-async-await-updated-extension.swift
Created
August 26, 2024 05:07
-
-
Save tonyarnold/749912b8c541cef4e2e6d6ce2c898628 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