RxSwift笔记 - Error Handling Operators
程序员文章站
2022-07-14 22:29:54
...
CatchError
从一个错误事件中恢复,将错误事件替换成一个备选序列
let sequenceThatFails = PublishSubject<String>()
let recoverySequence = PublishSubject<String>()
sequenceThatFails.catchError { (error) -> Observable<String> in
print("error: ", error)
return recoverySequence
}.subscribe(onNext: {
print($0)
}).disposed(by: disposeBag)
sequenceThatFails.onNext("A")
sequenceThatFails.onNext("B")
sequenceThatFails.onNext("C")
sequenceThatFails.onNext("D")
sequenceThatFails.onError(HHError(name: "test"))
recoverySequence.onNext("1")
recoverySequence.onNext("2")
/*
A
B
C
D
error: __lldb_expr_144.HHError
1
2
*/
CatchErrorJustReturn
会将 error 事件替换成其他的一个元素,然后结束该序列
sequenceThatFails.catchErrorJustReturn("666")
.subscribe(onNext: {
print($0)
}).disposed(by: disposeBag)
sequenceThatFails.onNext("1")
sequenceThatFails.onNext("2")
sequenceThatFails.onNext("3")
sequenceThatFails.onError(HHError(name: "test"))
/*
666
*/
Retry
如果源 Observable 产生一个错误事件,重新对它进行订阅,希望它不会再次产生错误
var count = 1
let canErrorSequence = Observable<String>.create { (observer) -> Disposable in
observer.onNext("A")
observer.onNext("B")
observer.onNext("C")
if count == 1 {
observer.onError(HHError.init(name: "text"))
print("Error encountered")
count += 1
}
observer.onNext("1")
observer.onNext("2")
observer.onNext("3")
observer.onCompleted()
return Disposables.create()
}
canErrorSequence.retry().subscribe(onNext: {
print($0)
}).disposed(by: disposeBag)
/*
A
B
C
Error encountered
A
B
C
1
2
3
*/
Debug
将 debug 调试操作符添加到一个链式步骤当中,这样系统就能将所有的订阅者、事件、和处理等详细信息打印出来,方便我们开发调试
/// debug() 不传参数 打印当前方法名
Observable.of("A", "B", "C", "D", "E", "F", "G").debug().subscribe(onNext: {
print($0)
}).disposed(by: disposeBag)
/// debug() 传参数 打印参数名
Observable.of("A", "B", "C", "D", "E", "F", "G").debug("调试:").subscribe(onNext: {
print($0)
}).disposed(by: disposeBag)