Wrapping the request -> result cycle into own adapter(请求->结果周期包装成自己的适配器)--Moya文档

Wrapping the request -> result cycle into own adapter(请求- >结果周期包装成自己的适配器)

看向一个真实世界的例子,你可能想把请求- >结果周期包装成自己的网络适配器,然后它变得更加容易响应成功、错误、或者网络失败后的重连等等

struct Network {
    static let provider = MoyaProvider(endpointClosure: endpointClosure)

    static func request(
        target: MyService,
        success successCallback: (JSON) -> Void,
        error errorCallback: (statusCode: Int) -> Void,
        failure failureCallback: (MoyaError) -> Void
    ) {
        provider.request(target) { result in
            switch result {
            case let .success(response):
                do {
                    try response.filterSuccessfulStatusCodes()
                    let json = try JSON(response.mapJSON())
                    successCallback(json)
                }
                catch error {
                    errorCallback(error)
                }
            case let .failure(error):
                if target.shouldRetry {
                    retryWhenReachable(target, successCallback, errorCallback, failureCallback)
                }
                else {
                    failureCallback(error)
                }
            }
        }
    }
}

// usage:
Network.request(.zen, success: { zen in
    showMessage(zen)
}, error: { err in
    showError(err)
}, failure: { _ in
    // oh well, no network apparently
})

总结 这小节的核心:

  1. 把Moya中的自己的请求-响应过程自己在封装一下,方便使用(只响应结果)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,909评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,845评论 18 139
  • 我的笔记本电脑的工作电压是20V,而我国的家庭用电是220V,如何让20V的笔记本电脑能够在220V的电压下工作?...
    justCode_阅读 1,443评论 0 5
  • 我的笔记本电脑的工作电压是20V,而我国的家庭用电是220V,如何让20V的笔记本电脑能够在220V的电压下工作?...
    justCode_阅读 754评论 0 1
  • "每个孩子都可以成为一个冠军, 我们永远不会放弃他们, 我们懂得连接的强大力量, 坚信他们可以成为那个最好的自己。...
    艳滨阅读 561评论 3 2