Created
August 2, 2019 22:07
-
-
Save nrivard/3b84cbc6c46b5aa3c619595b9dc02fb9 to your computer and use it in GitHub Desktop.
Using Result<Success, Failure> with Combine
This file contains hidden or 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
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