Objective
In this article we will learn RxSwift
about error handling, including:
- Catcherrorjustreturn
- Catcherror
- Retry
- Retry (_:)
Catcherrorjustreturn
error
When an event is encountered, it returns a value and ends. More details
let disposeBag = DisposeBag() let sequenceFail = PublishSubject<String>() sequenceFail.catchErrorJustReturn("??").subscribe(onNext: {print($0)}).disposed(by: disposeBag) sequenceFail.onNext("??")sequenceFail.onNext("??")sequenceFail.onError(TestError.test)
Operation Result:
??????
Catcherror
The capture error
is processed and can be returned sequence
to another subscription. More details
let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject<String>()let recoverySequence = PublishSubject<String>() sequenceThatFails.catchError { print("Error:", $0) return recoverySequence }.subscribe { print($0) }.disposed(by: disposeBag) sequenceThatFails.onNext("??")sequenceThatFails.onNext("??")sequenceThatFails.onNext("??")sequenceThatFails.onError(TestError.test) recoverySequence.onNext("??")
Operation Result:
next(??)next(??)next(??)Error: testnext(??)
Retry
Encountering the error event can be retried, such as a failed network request and can be reconnected. More details
let disposeBag = DisposeBag()var count = 1 let retrySequence = Observable<String>.create { (observer) -> Disposable in observer.onNext("??") observer.onNext("??") if count == 1 { observer.onError(TestError.test) print("Error encountered") count += 1 } observer.onNext("??") observer.onNext("??") return Disposables.create()} retrySequence.retry().subscribe(onNext: {print($0)}).disposed(by: disposeBag)
Operation Result:
????Error encountered????????
Retry (_:)
And
retry
Is the same, only the number of retries is specified.
let disposeBag = DisposeBag()var count = 1 let sequenceThatErrors = Observable<String>.create { observer in observer.onNext("??") observer.onNext("??") observer.onNext("??") if count < 5 { observer.onError(TestError.test) print("Error encountered") count += 1 } observer.onNext("??") observer.onNext("??") observer.onCompleted() return Disposables.create()} sequenceThatErrors.retry(3).subscribe(onNext: { print($0) }).disposed(by: disposeBag)
Operation Result:
??????Error encountered??????Error encountered??????Error encounteredReceived unhandled error: Playground.xcplaygroundpage:41:__lldb_expr_18 -> test
Thanks
If you find the wrong place, welcome to comment, thanks!
RxSwift Series (eight)