从可观察对象的错误通知中恢复的操作符
catchErrorJustReturn
- 从错误事件中恢复,方法是返回一个可观察到的序列,该序列发出单个元素,然后终止
let sequenceFails = PublishSubject<String>()
sequenceFails.catchErrorJustReturn("catchError")
.subscribe{print($0)}
.disposed(by:disposeBag)
sequenceFails.onNext("test")
sequenceFails.onNext(custError)
** catchError **
- 通过切换到提供的恢复可观察序列,从错误事件中恢复
let recoverySequence = PublishSubject<String>()
sequenceThatFails
.catchError {
print("Error:", $0)
return recoverySequence // 获取到了错误序列-我们在中间的闭包操作处理完毕,返回给用户需要的序列(showAlert)
}
.subscribe { print($0) }
.disposed(by: disposeBag)
sequenceThatFails.onNext("A")
sequenceThatFails.onNext("B") // 正常序列发送成功的
sequenceThatFails.onError(error) // 发送失败的序列
recoverySequence.onNext("C")
retry
通过无线的重新订阅可观察序列来恢复重复操作
var count = 1 // 外界变量控制流程
let sequenceRetryErrors = Observable<String>.create { observer in
observer.onNext("1")
observer.onNext("2")
observer.onNext("3")
if count == 1 {
// 流程进来之后就会过度-这里的条件可以作为出口,失败的次数
observer.onError(self.error) // 接收到了错误序列,重试序列发生
print("错误序列来了")
count += 1
}
observer.onNext("A")
observer.onNext("B")
observer.onNext("C")
observer.onCompleted()
return Disposables.create()
}
sequenceRetryErrors
.retry()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
网友评论