美文网首页
Wrapping the request -> result c

Wrapping the request -> result c

作者: 心印印心 | 来源:发表于2017-06-29 21:09 被阅读0次

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中的自己的请求-响应过程自己在封装一下,方便使用(只响应结果)

相关文章

网友评论

      本文标题:Wrapping the request -> result c

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