RxNetwork
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
要求
- iOS 9.0
- Swift 5.0
安装
RxNetwork 可通过 CocoaPods 或 Carthage 获取。要安装它,只需将以下行添加到您的 Podfile 或 Cartfile
Podfile
pod 'RxNetwork'
缓存
pod 'RxNetwork/Cacheable'
Cartfile
github "Pircate/RxNetwork"
使用方法
导入
import RxNetwork
配置
Network.Configuration.default.timeoutInterval = 20
Network.Configuration.default.plugins = [NetworkIndicatorPlugin()]
Network.Configuration.default.replacingTask = { target in
// configure common parameters etc.
switch target.task {
case let .requestParameters(parameters, encoding):
let params: [String: Any] = ["token": "", "sign": "", "body": parameters]
return .requestParameters(parameters: params, encoding: encoding)
default:
return target.task
}
}
// or
let configuration = Network.Configuration()
configuration.timeoutInterval = 20
configuration.plugins = [NetworkIndicatorPlugin()]
Network.Configuration.default = configuration
允许存储策略
确保缓存的数据是正确的 JSON 格式,否则解析数据时将失败并导致抛出异常。
如下,只有当 code 为 200 时返回的数据才是正确的 JSON 格式。
extension Storable where Self: TargetType {
public var allowsStorage: (Moya.Response) -> Bool {
return {
do {
return try $0.mapCode() == 200
} catch {
return false
}
}
}
}
无缓存请求
StoryAPI.latest
.request()
.map(StoryListModel.self)
.subscribe(onSuccess: { (model) in
}).disposed(by: disposeBag)
带缓存请求
/*
{
"top_stories": []
}
*/
StoryAPI.latest
.onCache(StoryListModel.self, { (model) in
})
.request()
.subscribe(onSuccess: { (model) in
})
.disposed(by: disposeBag)
StoryAPI.latest
.cache
.request()
.map(StoryListModel.self)
.subscribe(onNext: { (model) in
}).disposed(by: disposeBag)
/*
{
"code": 2000,
"message": "Ok",
"result": []
}
*/
TestTarget.test(count: 10)
.onCache([TestModel].self, { (models) in
})
.requestObject()
.subscribe(onSuccess: { (models) in
})
.disposed(by: disposeBag)
TestTarget.test(count: 10)
.cache
.request()
.mapObject([TestModel].self)
.subscribe(onNext: { (models) in
})
.disposed(by: disposeBag)
可缓存
为 target
提供缓存功能,请遵循 Cacheable
协议
enum API: TargetType, Cacheable {
case api
// 设置缓存过期时间
var expiry: Expiry {
return .never
}
}
作者
Pircate, [email protected]
许可证
RxNetwork 可在 MIT 许可证下使用。有关更多信息,请参阅 LICENSE 文件。