Last active
September 30, 2021 17:07
-
-
Save mihai8804858/9e1e12297df1ecad733d2bf5ea305a09 to your computer and use it in GitHub Desktop.
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
enum Either<T, U> { | |
case left(T) | |
case right(U) | |
} | |
... | |
/// Defines strategy to be used when determining if API response is `Empty`. | |
/// Available strategies are: 204 response code, 0 bytes and empty JSON container. | |
enum EmptyPredicate { | |
/// API returns 204 status code | |
case noContent | |
/// API returns 0 bytes | |
case noData | |
/// API returns empty json container | |
case emptyContainer | |
} | |
extension GravityResponse where Model == Data { | |
func isEmpty(for predicate: EmptyPredicate) -> Bool { | |
switch predicate { | |
case .noContent: | |
return statusCode == 204 | |
case .noData: | |
return rawData.isEmpty | |
case .emptyContainer: | |
guard let jsonObject = try? JSONSerialization.jsonObject(with: model, options: []), | |
let dictionary = jsonObject as? [String: Any] else { return false } | |
return dictionary.isEmpty | |
} | |
} | |
} | |
... | |
extension Provider { | |
func requestEither<T: TargetType, M: Decodable>( | |
target: T, | |
predicate: EmptyPredicate | |
) -> Observable<GravityResponse<Either<M, Void>>> { | |
request(target: target) | |
.flatMap { self.decode(response: $0, predicate: predicate) } | |
} | |
private func decode<M: Decodable>( | |
response: GravityResponse<Data>, | |
predicate: EmptyPredicate | |
) -> Observable<GravityResponse<Either<M, Void>>> { | |
Observable<GravityResponse<Either<M, Void>>>.create { observer in | |
if response.isEmpty(for: predicate) { | |
observer.onNext(response.map { _ in .right(()) }) | |
observer.onCompleted() | |
} else { | |
switch response.decode(M.self) { | |
case .success(let response): | |
observer.onNext(response.map { _ in .left(response.model) }) | |
observer.onCompleted() | |
case .failure(let error): | |
observer.onError(error) | |
} | |
} | |
return Disposables.create() | |
}.subscribe(on: ConcurrentDispatchQueueScheduler(qos: .utility)).observe(on: MainScheduler.instance) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment