Skip to content

Instantly share code, notes, and snippets.

@T1T4N
Last active June 21, 2024 12:17
Show Gist options
  • Save T1T4N/7fc3414c8c5629ef0335e44dd2fc0f10 to your computer and use it in GitHub Desktop.
Save T1T4N/7fc3414c8c5629ef0335e44dd2fc0f10 to your computer and use it in GitHub Desktop.
A Swift Extension for converting a Combine Publisher to async/await
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