Pod ‘Moya/RxSwift’ data request comes back and adds a layer of Rx between Moya and Your App
- Return model:
func homeListRequest(username: String, complete:@escaping ((Array<LGModel>) -> Void))
, - Return sequence:
func homeListRequestOB(username: String) -> Observable<LGRsult>
//LGLoginClient.swift
import UIKit
import Moya
import RxSwift
import HandyJSON
class LGLoginClient: NSObject {
static letManager = LGLoginClient() //MARK: 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 == "Request successful"{ complete(model.models ?? Func homeListRequestOB(username: String) -> Observable<LGRsult>{let provide = MoyaProvider<LGLoginAPI>()
return provide.rx.request(.homelist(username)).asObservable()
.mapModel(LGRsult.self)
}
}
Copy the code
- to
Moya
In theResponse
extensionObservableType
Protocol, implementationflatMap
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 {// Fault tolerant, no data returned!if data.count < 1 {
print("Serialization-modelable")
if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "{}") {return emptyValue
} else if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "[the] {}") {returnEmptyValue}} // Get the data requesting response and convert it to JSONlet jsonString = String.init(data: data, encoding: .utf8)
if let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
return model
}
return JSONDeserializer<T>.deserializeFrom(json: "{\"status\":\" Request error \"}")! }}Copy the code