RxSwift (8) 错误处理

catchErrorJustReturn

发送错误信号的时候,转换为指定的信息 发送

func rx_catchErrorJustReturn() {
    let disposeBag = DisposeBag()

    let sequenceThatFails = PublishSubject()

    sequenceThatFails
        .catchErrorJustReturn("haveError is timeout")
        .subscribe { print($0) }
        .disposed(by: disposeBag)

    sequenceThatFails.onNext("1")
    sequenceThatFails.onNext("2")
    sequenceThatFails.onNext("3")
    sequenceThatFails.onNext("4")
    sequenceThatFails.onError(RxError.timeout)
}
打印结果:
next(1)
next(2)
next(3)
next(4)
next(haveError is timeout)
completed

catchErrorJustReturn

发生错误,返回另一个 序列 继续订阅

func rx_catchError() {
    let disposeBag = DisposeBag()

    let sequenceThatFails = PublishSubject()
    let recoverySequence = PublishSubject()

    sequenceThatFails
        .catchError {
            print("Error:", $0)
            return recoverySequence
        }
        .subscribe { print($0) }
        .disposed(by: disposeBag)

    sequenceThatFails.onNext("1")
    sequenceThatFails.onNext("2")
    sequenceThatFails.onNext("3")
    sequenceThatFails.onNext("4")
    sequenceThatFails.onError(TestError.test)

    recoverySequence.onNext("5")
}
打印结果
next(1)
next(2)
next(3)
next(4)
Error: test//发生错误信号,切换序列继续订阅
next(5)

retry

遇见error事件进行重试,retry(3)重试3次,retry()无参重试一次

func rx_retry() {
    let disposeBag = DisposeBag()
    var count = 1

    let sequenceThatErrors = Observable.create { observer in
        observer.onNext("1")
        observer.onNext("2")
        observer.onNext("3")

        if count == 1 {
            observer.onError(TestError.test)
            print("Error encountered")
            count += 1
        }

        observer.onNext("4")
        observer.onNext("5")
        observer.onNext("6")
        observer.onCompleted()

        return Disposables.create()
    }

    sequenceThatErrors
        .retry()
        .subscribe(onNext: { print($0) })
        .disposed(by: disposeBag)
}
/*:
 ----
 ## `retry(_:)`
Recovers repeatedly from Error events by resubscribing to the `Observable` sequence, up to `maxAttemptCount` number of retries. [More info](http://reactivex.io/documentation/operators/retry.html)
 ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/retry.png)
 */
打印结果
1
2
3
Error encountered
1
2
3
4
5
6

你可能感兴趣的:(swift,Rx)