Pircate / RxNetwork

A swift network library based on Moya/RxSwift.
MIT License
50 stars 4 forks source link
cache moya rxswift

RxNetwork

CI Status Version Carthage compatible License Platform codebeat badge

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

Installation

RxNetwork is available through CocoaPods or Carthage. To install it, simply add the following line to your Podfile or Cartfile:

Podfile

pod 'RxNetwork'

缓存

pod 'RxNetwork/Cacheable'

Cartfile

github "Pircate/RxNetwork"

Usage

Import

import RxNetwork

Configuration

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

Allow storage strategy

确保缓存的数据是正确的 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
            }
        }
    }
}

Request without cache

StoryAPI.latest
    .request()
    .map(StoryListModel.self)
    .subscribe(onSuccess: { (model) in

    }).disposed(by: disposeBag)

Request with cache

/*
 {
    "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)

Cacheable

target 提供缓存功能,请遵循 Cacheable 协议

enum API: TargetType, Cacheable {
    case api

// 设置缓存过期时间
    var expiry: Expiry {
        return .never
    }
}

Author

Pircate, gao497868860@163.com

License

RxNetwork is available under the MIT license. See the LICENSE file for more info.