Skip to content

Instantly share code, notes, and snippets.

@nrivard
Created August 2, 2019 22:07
Show Gist options
  • Save nrivard/3b84cbc6c46b5aa3c619595b9dc02fb9 to your computer and use it in GitHub Desktop.
Save nrivard/3b84cbc6c46b5aa3c619595b9dc02fb9 to your computer and use it in GitHub Desktop.
Using Result<Success, Failure> with Combine
import Combine
extension Publisher {
/// A single value sink function that coalesces either one `Output` or one `Failure` as a `Result`-type.
public func sink(result: @escaping ((Result<Self.Output, Self.Failure>) -> Void)) -> AnyCancellable {
return sink(receiveCompletion: { completion in
switch completion {
case .failure(let error):
result(.failure(error))
case .finished:
break
}
}, receiveValue: { output in
result(.success(output))
})
}
}
let cancellable = somePublisher.sink { result in
do {
let success = try result.get()
// We did it.
} catch {
log(error)
// alert the user of complete failure
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment