美文网首页
RxSwift (retry, catchErrorJustRe

RxSwift (retry, catchErrorJustRe

作者: Hellolad | 来源:发表于2017-10-30 23:44 被阅读118次

    为了更加好的表现retry和catchErrorJustReturn的用法我们先用node.js写一个返回JSON的server.js。

    var http = require("http");
    
    var body = {
        "data": {
            "userName": "Bartholomew大熊"
        }
    }
    var bodyString = JSON.stringify(body);
    
    http.createServer(function (request, response) {
    
        response.writeHead(200, {'Content-Type': 'text/json'});
        response.write(bodyString)
        response.end();
    
    }).listen(8888);
    
    console.log('Server running at http://127.0.0.1:8888/')
    

    然后在终端 node server.js运行起来
    然后就是swift代码

    /**
     *  一旦序列里产出了一个error事件,整个序列将被终止。RxSwift主要有两种错误处理机制
     *  1.retry - 可以让序列在发生错误后重试
     *  2.catch - 可以在错误产生时,用一个备用元素或者一组备用元素将错误替换掉
     */
    
    import Foundation
    import UIKit
    import RxSwift
    import RxCocoa
    
    typealias JSON = Any
    
    struct ClassErrorHandling {
        private static let bag = DisposeBag()
        
        static func action() {
            //retry()
            catchError()
        }
        
        // retry
        private static func retry() {
            
            let json: Observable<JSON> = Observable<JSON>.create { (observer) -> Disposable in
                
                let dataTask = URLSession.shared.dataTask(with: URL(string: "http://127.0.0.1:8888/")!, completionHandler: { (data, response, error) in
                    guard error == nil else {
                        observer.onError(error!)
                        return
                    }
                    guard let data = data, let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) else {
                        observer.onError(CustomError.error)
                        return
                    }
                    observer.onNext(jsonObject)
                    observer.onCompleted()
                    
                })
                dataTask.resume()
                return Disposables.create()
            }
            
            json
                .retry(2)
                .subscribe(onNext: { json in
                    print("success = \(json)")
                }, onError: { error in
                    print("error = \(error)")
                }, onCompleted: {
                    print("completed")
                })
                .disposed(by: bag)
        }
        
        // catch
        private static func catchError() {
            let json: Observable<JSON> = Observable<JSON>.create { (observer) -> Disposable in
                
                let dataTask = URLSession.shared.dataTask(with: URL(string: "http://127.0.0.1:8888/")!, completionHandler: { (data, response, error) in
                    guard error == nil else {
                        observer.onError(error!)
                        return
                    }
                    guard let data = data, let jsonObject = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) else {
                        observer.onError(CustomError.error)
                        return
                    }
                    observer.onNext(jsonObject)
                    observer.onCompleted()
                    
                })
                dataTask.resume()
                return Disposables.create()
            }
            
            json
                .catchErrorJustReturn(["data": "9000"])
                .subscribe(onNext: { json in
                    print("success = \(json)")
                }, onError: { error in
                    print("error = \(error)")
                }, onCompleted: {
                    print("completed")
                })
                .disposed(by: bag)
        }
        
    }
    
    • 运行之后就能看到retry和catchErrorJustReturn的表现方式。

    相关文章

      网友评论

          本文标题:RxSwift (retry, catchErrorJustRe

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