阅读 790

Moya/RxSwift

pod 'Moya/RxSwift'数据请求回来在Moya和Your App之间加一层Rx

  • 返回模型:func homeListRequest(username: String, complete:@escaping ((Array<LGModel>) -> Void))
  • 返回序列:func homeListRequestOB(username: String) -> Observable<LGRsult>
//LGLoginClient.swift
import UIKit
import Moya
import RxSwift
import HandyJSON

class LGLoginClient: NSObject {
    static let manager = LGLoginClient()

    //MARK: - 首页列表请求
    func homeListRequest(username: String, complete:@escaping ((Array<LGModel>) -> Void)){
        let provide = MoyaProvider<LGLoginAPI>()
        _ = provide.rx.request(.homelist(username)).asObservable()
            .mapModel(LGRsult.self)
            .subscribe(onNext: { (model) in
                if model.status == "请求成功" {
                    complete(model.models ?? [LGModel()])
                }
            })
    }
    
    //MARK: - 首页列表请求
    func homeListRequestOB(username: String) -> Observable<LGRsult>{
        let provide = MoyaProvider<LGLoginAPI>()
        return provide.rx.request(.homelist(username)).asObservable()
            .mapModel(LGRsult.self)
    }
}
复制代码
  • Moya中的Response扩展ObservableType协议,实现flatMap
extension ObservableType where E == Response {
     public func mapModel<T: HandyJSON>(_ type: T.Type) -> Observable<T> {
        return flatMap({ (response) -> Observable<T> in
            return Observable.just(response.mapModel(T.self))
        })
    }
}

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) -> T {
        // 容错,没有数据返回!
        if data.count < 1 {
            print("序列化-模型化不了")
            if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "{}"){
                return emptyValue
            } else if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "[{}]"){
                return emptyValue
            }
        }
        // 获取请求response的data转成json
        let jsonString = String.init(data: data, encoding: .utf8)
        if let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
            return model
        }
        return JSONDeserializer<T>.deserializeFrom(json: "{\"status\":\"请求有误\"}")!

    }
}
复制代码