GithubHelp home page GithubHelp logo

rxnetwork's Introduction

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

  • iOS 9.0
  • Swift 5.0

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, [email protected]

License

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

rxnetwork's People

Contributors

pircate avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rxnetwork's Issues

缓存机制报错

/*
返回格式是以下,用对象去缓存正常
         {
         "top_stories": []
         }
         */  

Demo中下面此示例方法在解析过程中报错

/*
返回格式是以下,用数组对象去缓存报错
  {
   "code": 2000,
   "message": "Ok",
   "result": []
   }
*/
BannerAPI.test(count: 10)
      .onCache([BannerModel].self, { (models) in
          debugPrint("onCache:", models.first?.name ?? "")
      })
      .requestObject()
      .subscribe(onSuccess: { (models) in
          debugPrint("onSuccess:", models.first?.name ?? "")
      }, onError: { (error) in
          debugPrint("error:", error)
      })
     .disposed(by: disposeBag)

报错如下

Moya_Logger: [01/07/2019 17:56:24] Request: https://app01.chengtay.com:82/m/banner
Moya_Logger: [01/07/2019 17:56:24] Request Headers: ["Content-Type": "application/json"]
Moya_Logger: [01/07/2019 17:56:24] HTTP Request Method: POST
Moya_Logger: [01/07/2019 17:56:24] Request Body: {"sign":"","body":{"count":10},"token":""}
Moya_Logger: [01/07/2019 17:56:24] Response: <NSHTTPURLResponse: 0x600002f64140> { URL: https://app01.chengtay.com:82/m/banner } { Status Code: 200, Headers {
    "Cache-Control" =     (
        "no-cache",
        "no-store"
    );
    Connection =     (
        "keep-alive"
    );
    "Content-Type" =     (
        "application/json;charset=UTF-8"
    );
    Date =     (
        "Mon, 01 Jul 2019 09:56:24 GMT"
    );
    Expires =     (
        "Thu, 01 Jan 1970 00:00:00 GMT"
    );
    Pragma =     (
        "no-cache"
    );
    Server =     (
        "nginx/1.10.2"
    );
    "Set-Cookie" =     (
        "token=8621f0a4-48d0-4348-8fd3-eec3207ee863;Path=/; HttpOnly"
    );
    "Transfer-Encoding" =     (
        Identity
    );
} }
{
  "code" : 2000,
  "result" : [
    {
      "status" : 1,
      "img" : "banner\/20180920\/bb734a7e95f14a93a0edb8acbc572ad5.jpg",
      "content" : "https:\/\/www.chengtay.com\/",
      "id" : 11,
      "isDeleted" : 1,
      "createTime" : "2018-09-20 09:42:59",
      "updateTime" : "2018-11-01 14:29:24",
      "type" : 2,
      "description" : "https:\/\/www.chengtay.com\/",
      "name" : "公司",
      "pos" : null
    }
  ],
  "message" : "OK",
  "token" : "8621f0a4-48d0-4348-8fd3-eec3207ee863"
}
"error:" Moya.MoyaError.objectMapping(Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "result", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil)), Status Code: 200, Data Length: 368)

一些关于 podspec 文件的小建议。

  1. 可以把 swift_version 改到 "4.2",不然新安装库 Xcode 都会提示 convert 。
  2. ios.deployment_target 可以从 8.0 开始支持,有些人还是会有从 8.0 开始适配的需求的。另外一个 CleanJSON 的库也可以改到从8.0开始。

这两个包括 CleanJSON 我都用私有库测试过,直接改就行,不用动主工程的任何代码。虽然修改 podspec 用私有库也能满足自己的需求,但还是支持一下官方比较好。

缓存问题

既然是缓存有效时间内,是不是cache后跟.request()的时候,在request里判断一下需不需要做一次不必要的请求。

Endpoint的自定义

let endpointClosure = { target -> Endpoint in
MoyaProvider.defaultEndpointMapping(for: target).replacing(task: configuration.taskClosure(target))
} 这个地方用的默认的Endpoint
要改变的话 是不是只能用Network.default.provider去设置了

OnCache 方法不支持指定路径的解析和缓存

Hello,我看了下你的实现,思路很好。
但是你在

public func request() -> Single<C> {
    return target.request().map(C.self).storeCachedObject(for: target)
}

这个方法中默认是拿到返回数据的根路径去解析和缓存的,假如我不想缓存根路径的模型,只想缓存某个路径的模型,是不支持的。
我知道可以把路径作为参数也写到这个 request 方法中,但是这样一来方法的语义看起来就没有那么优雅了。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.