Skip to content

Instantly share code, notes, and snippets.

@joeltrew
Created January 26, 2021 15:28
Show Gist options
  • Save joeltrew/0798af00371f05b183ed47324519453f to your computer and use it in GitHub Desktop.
Save joeltrew/0798af00371f05b183ed47324519453f to your computer and use it in GitHub Desktop.
Combine+ResultHelpers.swift
//
// Combine+Helpers.swift
//
import Foundation
import Combine
public extension Publisher {
func asResult<S, E: Error>() -> AnyPublisher<Result<S, E>, Never> where Self.Output == S, Self.Failure == E {
self
.map(Result.success)
.catch { error in Just(.failure(error)) }
.eraseToAnyPublisher()
}
}
public extension Publisher where Failure == Never {
func sinkResult<U, E>(
receiveSuccess: @escaping ((U) -> Void),
receiveFailure: @escaping ((E) -> Void)
) -> AnyCancellable where Output == Result<U, E> {
let subscriber = Subscribers.Sink<Output, Failure>(
receiveCompletion: { _ in },
receiveValue: { result in
switch result {
case .success(let value):
receiveSuccess(value)
case .failure(let failure):
receiveFailure(failure)
}
}
)
subscribe(subscriber)
return AnyCancellable(subscriber)
}
func ignoreFailure<U, E>()-> AnyPublisher<U, Never> where Self.Output == Result<U, E> {
self.tryMap {
try $0.get()
}
.catch { _ in Empty<U, Never>() }
.eraseToAnyPublisher()
}
func handleAsCompletion<U, E: Error>(completion: @escaping (Result<U, E>) -> Void) where Output == Result<U, E> {
let subscriber = Subscribers.Sink<Output, Failure>(
receiveCompletion: { _ in },
receiveValue: { result in
completion(result)
}
)
self.subscribe(subscriber)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment