Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Forked from nrivard/combine+result.swift
Created August 2, 2022 21:31
Show Gist options
  • Save andresr-dev/a58badba805d005a0cd70ec3ab201f77 to your computer and use it in GitHub Desktop.
Save andresr-dev/a58badba805d005a0cd70ec3ab201f77 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