Apr 10, 2024
Try this. The nil assignment is needed in order to capture the cancellable
extension Publisher {
func asyncResult() async throws -> Output {
try await withCheckedThrowingContinuation { continuation in
var cancellable: AnyCancellable?
cancellable = self.sink(
receiveCompletion: {
switch $0 {
case .failure(let error):
continuation.resume(throwing: error)
case .finished:
cancellable = nil
}
}, receiveValue: {
continuation.resume(returning: $0)
}
)
}
}
}