Skip to content

Instantly share code, notes, and snippets.

@piotrbernad
Created September 27, 2017 18:56
Show Gist options
  • Save piotrbernad/ba0247469ed3c5c9cfb0d59c786e530f to your computer and use it in GitHub Desktop.
Save piotrbernad/ba0247469ed3c5c9cfb0d59c786e530f to your computer and use it in GitHub Desktop.
API
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