Skip to content

Instantly share code, notes, and snippets.

@woodycatliu
Created February 28, 2023 14:03
Show Gist options
  • Save woodycatliu/b9c0e547a8d6e72a090ba2b2959d2c5a to your computer and use it in GitHub Desktop.
Save woodycatliu/b9c0e547a8d6e72a090ba2b2959d2c5a to your computer and use it in GitHub Desktop.
Combine to async
extension Publisher {
func awaitOutput() async throws -> Output {
return try await withCheckedThrowingContinuation { continuation in
let lock = NSRecursiveLock()
var nillableContinuation: CheckedContinuation<Self.Output, Error>? = continuation
var cancelable: AnyCancellable?
cancelable = first().sink(receiveCompletion: {
lock.lock(); defer { lock.unlock() }
switch $0 {
case .failure(let error):
nillableContinuation?.resume(throwing: error)
default: break
}
nillableContinuation = nil
cancelable?.cancel()
}, receiveValue: {
lock.lock(); defer { lock.unlock() }
nillableContinuation?.resume(returning: $0)
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment