RxSwift学习之旅-错误处理

开始之前首先开启Playground的needsIndefiniteExecution,以保证我们之后的延时操作能够正常运行,在你的Playground添加以下代码

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
retry

先来看看 retry ,可能这个操作会比较常用,一般用在网络请求失败时,再去进行请求。
retry 就是失败了再尝试,重新订阅一次序列。

example(of: "retry") {
    var count = 1
    let funnyLookingSequence = Observable.create({ (observer) -> Disposable in
        let error = NSError(domain: "test", code: 0, userInfo: nil)
        observer.onNext(1)
        observer.onNext(2)
        observer.onNext(3)
        if count < 2 {
            observer.onError(error)
            count += 1
        }
        observer.onNext(4)
        observer.onNext(5)
        observer.onNext(6)
        return Disposables.create()
    })
    
    funnyLookingSequence.retry(2).subscribe({
        print($0)
    })
}
--- Example of: retry ---
next(1)
next(2)
next(3)
next(1)
next(2)
next(3)
next(4)
next(5)
next(6)

需要注意的是不加参数的 retry 会无限尝试下去。我们还可以传递一个 Int 值,来说明最多尝试几次。像这样 retry(2) ,最多尝试两次。

cacheError

出现 Error 时,用一个新的序列替换。

example(of: "cacheError") {
    let sequenceThatFails = PublishSubject()
    let recoverySequence = Observable.of(100,200,300)
    
    sequenceThatFails.catchError({ (error) -> Observable in
        return recoverySequence
    }).subscribe({
        print($0)
    })
    
    sequenceThatFails.onNext(1)
    sequenceThatFails.onNext(2)
    sequenceThatFails.onNext(3)
    sequenceThatFails.onError(NSError(domain: "test", code: 2, userInfo: nil))
    sequenceThatFails.onNext(4)
}
--- Example of: cacheError ---
next(1)
next(2)
next(3)
next(100)
next(200)
next(300)
completed

catchError 中你需要传递一个返回序列的闭包。

catchErrorJustReturn

catchErrorJustReturn遇到错误,返回一个值替换这个错误。

example(of: "catchErrorJustReturn") {
    let sequenceThatFails = PublishSubject()
    
    sequenceThatFails.catchErrorJustReturn(100).subscribe({
        print($0)
    })
    
    sequenceThatFails.onNext(1)
    sequenceThatFails.onNext(2)
    sequenceThatFails.onNext(3)
    sequenceThatFails.onError(NSError(domain: "test", code: 2, userInfo: nil))
}
--- Example of: catchErrorJustReturn ---
next(1)
next(2)
next(3)
next(100)
completed

你可能感兴趣的:(RxSwift学习之旅-错误处理)