Created
July 14, 2020 17:18
-
-
Save IanKeen/458957673d70ac18d9cbbcf6b719ac69 to your computer and use it in GitHub Desktop.
Extension to convert a failable Publisher into a non-failable Result based publisher (as well as extensions to break out values/errors) - Same idea as RxSwifts Materialize
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
extension Publisher { | |
func asResult() -> AnyPublisher<Result<Output, Failure>, Never> { | |
return map(Result.success) | |
.catch { Just(Result.failure($0)) } | |
.eraseToAnyPublisher() | |
} | |
} | |
extension Publisher { | |
func values<S, F: Error>() -> AnyPublisher<S, Never> where Output == Result<S, F>, Failure == Never { | |
return flatMap { (result) -> AnyPublisher<S, Never> in | |
switch result { | |
case .success(let value): | |
return Just(value).eraseToAnyPublisher() | |
case .failure: | |
return Empty().eraseToAnyPublisher() | |
} | |
}.eraseToAnyPublisher() | |
} | |
func errors<S, F: Error>() -> AnyPublisher<F, Never> where Output == Result<S, F>, Failure == Never { | |
return flatMap { (result) -> AnyPublisher<F, Never> in | |
switch result { | |
case .success: | |
return Empty().eraseToAnyPublisher() | |
case .failure(let error): | |
return Just(error).eraseToAnyPublisher() | |
} | |
}.eraseToAnyPublisher() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment