Skip to content

Instantly share code, notes, and snippets.

@celian-m
Created December 20, 2018 09:13
Show Gist options
  • Save celian-m/784cd653e3481ff324d26d6b2bf9aced to your computer and use it in GitHub Desktop.
Save celian-m/784cd653e3481ff324d26d6b2bf9aced to your computer and use it in GitHub Desktop.
Rx variation for UseCase declaration
import Foundation
import RxSwift
enum Either<T> {
case success(T)
case error(Swift.Error)
var successResult: T? {
switch self {
case .success(let result):
return result
case .error(_):
return nil
}
}
}
protocol UseCaseProtocol {
associatedtype ReturnType
associatedtype Param
func execute(_ params: Param, completion: @escaping ((Either<ReturnType>) -> Void))
}
struct UseCase<P, R> {
typealias ReturnType = R
typealias Param = P
init<U>(_ useCase: U) where U: UseCaseProtocol, U.ReturnType == ReturnType, U.Param == Param {
_execute = useCase.execute
}
func execute(_ params: P, completion: @escaping ((Either<R>) -> Void)) {
_execute(params, completion)
}
func execute(_ params: P) -> Observable<R> {
return Observable.create { (observable) in
self._execute(params) { (either) in
switch either {
case .success(let response):
observable.onNext(response)
case .error(let error):
observable.onError(error)
}
observable.onCompleted()
}
return Disposables.create()
}
}
let _execute: (P, @escaping (Either<R>) -> Void) -> Void
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment