美文网首页
Swift 网络请求 : Moya+RxSwift

Swift 网络请求 : Moya+RxSwift

作者: li_礼光 | 来源:发表于2018-07-17 16:58 被阅读128次

Moya+RxSwift.swift

源文档内容
extension MoyaProvider: ReactiveExtensionsProvider {}
public extension Reactive where Base: MoyaProviderType {
    /// 指定的请求制作方法。
    public func request(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> SignalProducer<Response, MoyaError> {
        return SignalProducer { 
            ........//具体代码看源文档
        }
    }

    ///带进度的指定请求制作方法。
    public func requestWithProgress(_ token: Base.Target, callbackQueue: DispatchQueue? = nil) -> SignalProducer<ProgressResponse, MoyaError> {
        let progressBlock: (Signal<ProgressResponse, MoyaError>.Observer) -> (ProgressResponse) -> Void = { observer in
            return { progress in
            ........//具体代码看源文档
            }
    }
}

简单的从上面看到,Moya+RxSwift.swift中,带有两个方法.


Swfit Moya专题 : 使用理解中的请求代码一样,创建一个MoyaProvider<MoyaApi>()对象

Moya+RxSwift写法
let rxProvider = MoyaProvider<MoyaApi>()
rxProvider.rx.request(.login(account: "15876450119", password: "123123qwe")).subscribe(onSuccess: { (response) in
    print("response = \(response)")
    print("response = \(String(describing: response.response))")
    print("response = \(String(describing: response.request))")
    print("response = \(response.description)")
    guard let json = try? JSONSerialization.jsonObject(with: response.data, options: .mutableContainers) else {
        return
    }
        print("response = \(String(describing: json))")
    }) { (error) in
        print("error = \(error)")
    }
纯Moya写法
let provider = MoyaProvider<MoyaApi>()
provider.request(MoyaApi.login(account: "15876450119", password: "123123qwe"), callbackQueue: nil, progress: { (response) in
    print("response = \(response)")
    }) { (result) in
        switch result {
            case let .success(result):
            do {
                try print("result.mapJSON() = \(result.mapJSON())")
            } catch {
                print("MoyaError.jsonMapping(result) = \(MoyaError.jsonMapping(result))")
            }
            default:
                break
            }
            print("result = \(result.description)")
        }

其实一对比看就很简单了.

相关文章

网友评论

      本文标题:Swift 网络请求 : Moya+RxSwift

      本文链接:https://www.haomeiwen.com/subject/dqzwpftx.html