Created
February 28, 2023 14:03
-
-
Save woodycatliu/b9c0e547a8d6e72a090ba2b2959d2c5a to your computer and use it in GitHub Desktop.
Combine to async
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
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