Created
March 22, 2017 14:25
-
-
Save desmondmc/f23322f0de1be809f0a7ee8bbee808e9 to your computer and use it in GitHub Desktop.
Result Type Goodies
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
import RxSwift | |
import RxCocoa | |
enum Result<T>: ResultType { | |
case success(T) | |
case failure(Error) | |
var data: T? { | |
switch self { | |
case .success(let d): | |
return d | |
default: | |
return nil | |
} | |
} | |
var error: Error? { | |
switch self { | |
case .failure(let e): | |
return e | |
default: | |
return nil | |
} | |
} | |
} | |
protocol ResultType { | |
associatedtype T | |
var data: T? {get} | |
var error: Error? {get} | |
} | |
extension ObservableType where E: ResultType { | |
func filterSuccess() -> Observable<E.T> { | |
return flatMap { result -> Observable<E.T> in | |
if let data = result.data { | |
return Observable.just(data) | |
} | |
return Observable.empty() | |
} | |
} | |
} | |
extension ObservableType where E: ResultType { | |
func filterFailure() -> Observable<Error> { | |
return flatMap { result -> Observable<Error> in | |
if let error = result.error { | |
return Observable.just((error)) | |
} | |
return Observable.empty() | |
} | |
} | |
} | |
extension ObservableType { | |
func driveResult() -> Driver<Result<E>> { | |
return self.map { Result.success($0) } | |
.asDriver(onErrorRecover: { Driver.just(.failure($0)) }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment