Skip to content

Instantly share code, notes, and snippets.

@vknabel
Last active January 11, 2017 17:47
Show Gist options
  • Save vknabel/c73a79fe5b4f12d8edba8bf3de1a9532 to your computer and use it in GitHub Desktop.
Save vknabel/c73a79fe5b4f12d8edba8bf3de1a9532 to your computer and use it in GitHub Desktop.
Wraps RxBlocking for Result
import RxBlocking
import RxSwift
import Result
/// `BlockingResultObservables` provide convenience methods for gaining a `Result` out of `Observables`.
///
/// It may be useful for testing purposes
/// or for preventing CLIs to be terminated too early,
/// but usually you should not use it in production code.
///
/// Try to stay in observable context instead.
public struct BlockingResultObservable<E> {
fileprivate let blocking: BlockingObservable<E>
fileprivate init(source: Observable<E>, timeout: RxTimeInterval?) {
blocking = source.toBlocking(timeout: timeout)
}
}
public extension BlockingResultObservable {
public func toArray() -> Result<[E], AnyError> {
return materialize(try blocking.toArray())
}
public func first() -> Result<E?, AnyError> {
return materialize(try blocking.first())
}
public func single(_ predicate: @escaping (E) -> Bool = { _ in true }) -> Result<E?, AnyError> {
return materialize(try blocking.single(predicate))
}
}
public extension ObservableType {
public func toResulting(timeout: RxTimeInterval? = nil) -> BlockingResultObservable<E> {
return .init(source: self.asObservable(), timeout: timeout)
}
}
import RxSwift
import Result
public extension Observable {
static func from<ResultError: Error>(_ result: Result<E, ResultError>) -> Observable {
return Observable.from(result)
}
func materialize() -> Observable<Result<E, AnyError>> {
return map(Result.success)
.catchError({ .of(.failure(AnyError($0))) })
}
}
extension Result: ObservableType {
public func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == T {
return asObservable().subscribe(observer)
}
public typealias E = T
public func asObservable() -> Observable<T> {
switch self {
case let .success(value):
return .of(value)
case let .failure(error):
return .error(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment