Created
January 26, 2021 15:28
-
-
Save joeltrew/0798af00371f05b183ed47324519453f to your computer and use it in GitHub Desktop.
Combine+ResultHelpers.swift
This file contains 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
// | |
// 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