一、定義獲取緩存策略的接口緩存
import Foundation protocol CachePolicyGettable { var cachePolicy: URLRequest.CachePolicy {get} }
二、TargetType 實現該接口app
extension MoyaAPI: TargetType, CachePolicyGettable { var cachePolicy: URLRequest.CachePolicy { switch self { case .featured,.pizza,.categories: return .reloadIgnoringLocalCacheData } } ... }
三、實現PluginTypeide
extension MoyaAPI: TargetType, CachePolicyGettable { var cachePolicy: URLRequest.CachePolicy { switch self { case .featured,.pizza,.categories: return .reloadIgnoringLocalCacheData } }
四、應用PluginTypespa
let MoyaAPIPrivider = MoyaProvider<MoyaAPI>(plugins: [CachePolicyPlugin()]) func all() -> Observable<[FeaturedViewModel]> { let networkData = MoyaAPIPrivider.rx.request(.featured) .filterSuccessfulStatusCodes() .debug() .mapArray(Featured.self) .map{ item -> [FeaturedViewModel] in var viewModels: [FeaturedViewModel] = [] for model in item { try! model.createOrUpdate() let viewModel = FeaturedViewModel(model: model) viewModels.append(viewModel) } return viewModels }.asObservable() }