Moya/RxSwift + HandyJson 优雅的网络请求

!!!使用前了解下Moya的基础用法
1、导入库

pod 'Moya/RxSwift'
pod 'HandyJSON', '~>5.0.2'

2、为Response和ObservableType追加扩展为了做模型映射

extension ObservableType where E == Response {
     public func mappingModel(_ type: T.Type) -> Observable {
        return flatMap({ (response) -> Observable in
            return Observable.just(response.mappingModel(T.self))
        })
    }
}

extension Response {
    func mappingModel(_ type: T.Type) -> T {
        // 没有数据返回
        if data.count < 1 {
            if let emptyValue = JSONDeserializer.deserializeFrom(json: "{}"){
                return emptyValue
            } else if let emptyValue = JSONDeserializer.deserializeFrom(json: "[{}]"){
                return emptyValue
            }
        }
        // 获取请求response的data转成json
        let jsonString = String.init(data: data, encoding: .utf8)
        if let model = JSONDeserializer.deserializeFrom(json: jsonString) {
            return model
        }
        return JSONDeserializer.deserializeFrom(json: "{\"status\":\"request error\"}")!
    }
}

3、使用方法 TestAPI为enum遵守了TargetType协议

 MoyaProvider()
            .rx
            .request(.reciptRequset)
            .asObservable()
            .mappingModel(RecipeBannerResponse.self)
            .subscribe(onNext: { [weak self] (model) in

                //self?.mModel.accept(model.data?.first ?? RecipeDataModel())
                print("model: \(String(describing: model.data?.first))")
            }, onError: {(error) in
                print("error: \(error)")
            })
            .disposed(by: bag)

你可能感兴趣的:(Moya/RxSwift + HandyJson 优雅的网络请求)