Created
September 27, 2017 18:56
-
-
Save piotrbernad/ba0247469ed3c5c9cfb0d59c786e530f to your computer and use it in GitHub Desktop.
API
This file contains hidden or 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
| public struct API<T: TargetType> { | |
| fileprivate var provider: RxMoyaProvider<T> = RxMoyaProvider(plugins: [CachingPlugin()], trackInflights: true) | |
| private func request(_ endpoint: T) -> Observable<Response> { | |
| return provider.request(endpoint).asObservable() | |
| } | |
| public func request<O: JSONDecodable>(_ endpoint: T) -> Observable<O> { | |
| return provider.request(endpoint).asObservable().mapObject() | |
| } | |
| public func request<O: JSONDecodable>(_ endpoint: T) -> Observable<[O]> { | |
| return provider.request(endpoint).asObservable().mapObject() | |
| } | |
| } | |
| extension API where T: CachableTarget { | |
| public func provide<O: JSONDecodable>(_ endpoint: T) -> Observable<O> { | |
| let network: Observable<O> = self.request(endpoint) | |
| return self.cache(endpoint) | |
| .concat(network) | |
| } | |
| public func provide<O: JSONDecodable>(_ endpoint: T) -> Observable<[O]> { | |
| let network: Observable<[O]> = self.request(endpoint) | |
| return self.cache(endpoint) | |
| .concat(network) | |
| } | |
| public func cache<O: JSONDecodable>(_ endpoint: T) -> Observable<[O]> { | |
| let cache = CacheStorage(cacheKey: endpoint.cacheKey) | |
| guard let readObject: [O] = cache.read() else { | |
| return Observable.empty() | |
| } | |
| return Observable.just(readObject) | |
| } | |
| public func cache<O: JSONDecodable>(_ endpoint: T) -> Observable<O> { | |
| let cache = CacheStorage(cacheKey: endpoint.cacheKey) | |
| guard let readObject: O = cache.read() else { | |
| return Observable.empty() | |
| } | |
| return Observable.just(readObject) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment