RxSwift 操作符 (catchError)

catchError

ReactiveX:
The Catch operator intercepts an onError notification from the source Observable and, instead of passing it through to any observers, replaces it with some other item or sequence of items, potentially allowing the resulting Observable to terminate normally or not to terminate at all.

catchError会在要发生onError事件时将其拦截,并使用备用的序列替代它,再次执行操作。

let errorObservable = Observable<Int>.error(CatchError.error)
let intObservable = Observable<Int>.just(666)

errorObservable
    .catchError({ error in
        print("catch:", error)
        return intObservable
    })
    .subscribe { event in
        switch event {
        case .next(let element):
            print("element:", element)
        case .error(let error):
            print("error:", error)
        case .completed:
            print("completed")
        }}
    .disposed(by: bag)

输出:
catch: error
element: 666
completed

intObservable即是备用序列。

catchErrorJustReturn

catchErrorJustReturn仅仅是在获取到错误的时候返回一个备用的值。

猜你喜欢

转载自blog.csdn.net/weixin_38318852/article/details/80327064