(十二)RxSwift之错误与调试(Error & Debug)

874 阅读2分钟
操作符 描述
error 创建一个只会产生一个 error事件的Observable
catchErrorJustReturn 当遇到 error 事件的时候,就返回指定的值,然后结束
catchError 从一个错误事件中恢复,将错误事件替换成一个备选序列
retry 使用该方法当遇到错误的时候,会重新订阅该序列
debug 输出所有的订阅者、事件、和处理
RxSwift.Resources.total 查看当前 资源数量。检查内存泄露
  • error

error 操作符将创建一个 Observable,这个 Observable 只会产生一个 error 事件。 示例:

let _ = Observable<Int>.error(MError)
//==
let _ = Observable<Int>.create { observer in
    observer.onError(self.MError)
    return Disposables.create()
}
  • catchErrorJustReturn

当遇到 error 事件的时候,就返回指定的值,然后结束 示例:

let sequenceThatFails = PublishSubject<String>()

sequenceThatFails
    .catchErrorJustReturn("Maxiaoliao")
    .subscribe{ print($0, terminator: " ") }
    .disposed(by: disposeBag)

sequenceThatFails.onNext("apple")
sequenceThatFails.onNext("banana")// 正常序列发送成功的
sequenceThatFails.onError(MError)//发送失败的序列,一旦订阅到就 返回我们之前设定的错误的预案
//输出:next(apple) next(banana) next(Maxiaoliao) completed
  • catchError

从一个错误事件中恢复,将错误事件替换成一个备选序列

示例:

let sequenceThatFails = PublishSubject<String>()

let recoverySequence = PublishSubject<String>()

let _ = sequenceThatFails
        .catchError {
            print("Error:", $0)
            return recoverySequence //获取到了错误序列-我们在中间的闭包操作处理完毕,返回给用户需要的序列(showAlert)
        }
        .subscribe{ print($0, terminator: " ") }
        .disposed(by: disposeBag)

sequenceThatFails.onNext("apple")
sequenceThatFails.onNext("banana")// 正常序列发送成功的
recoverySequence.onNext("waterM")
recoverySequence.onNext("peach")
//输出:Error: Error Domain=马小撂 Code=10086 "(null)"
//next(waterM) next(peach)
//输出在onError事件后的所有recoverySequence
  • retry

使用该方法当遇到错误的时候,会重新订阅该序列,retry() 方法可以传入数字表示重试次数(默认1)。 示例:

var count = 1 //外界变量控制流程
let squenceThatErrors = Observable<String>.create { (observer) -> Disposable in
    observer.onNext("apple")
    observer.onNext("banana")
    observer.onNext("peach")
    if count < 5 {// 流程进来之后就会过度-这里的条件可以作为出口,失败的次数
        observer.onError(self.MError)
        print("错误序列来了")
        count += 1
    }
    observer.onNext("tea")
    observer.onNext("BlackTea")
    observer.onNext("GreenTea")
    observer.onCompleted()
    return Disposables.create()
}

squenceThatErrors
    .retry(3)
    .subscribe(onNext: {print($0, terminator: " ")})
    .disposed(by: disposeBag)
输出:
apple banana peach 错误序列来了
apple banana peach 错误序列来了
apple banana peach 错误序列来了
Unhandled error happened: Error Domain=马小撂 Code=10086 "(null)"
subscription called from:
  • debug

输出所有的订阅者、事件、和处理 示例:

var count = 1
let squenceThatErrors = Observable<String>.create { (observer) -> Disposable in
    observer.onNext("apple")
    observer.onNext("banana")
    observer.onNext("peach")
    if count < 5 {// 流程进来之后就会过度-这里的条件可以作为出口,失败的次数
        observer.onError(self.MError)
        print("错误序列来了")
        count += 1
    }
    observer.onNext("tea")
    observer.onNext("BlackTea")
    observer.onNext("GreenTea")
    observer.onCompleted()
    return Disposables.create()
}

squenceThatErrors
    .retry(3)
    .debug()
    .subscribe(onNext: {print($0, terminator: " ")})
    .disposed(by: disposeBag)
2019-10-27 17:42:20.753: MErrorAndDebugViewController.swift:190 (testDebug()) -> subscribed
2019-10-27 17:42:20.759: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(apple)
apple 2019-10-27 17:42:20.759: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(banana)
banana 2019-10-27 17:42:20.759: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(peach)
peach 错误序列来了
2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(apple)
apple 2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(banana)
banana 2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(peach)
peach 错误序列来了
2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(apple)
apple 2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(banana)
banana 2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event next(peach)
peach 错误序列来了
2019-10-27 17:42:20.760: MErrorAndDebugViewController.swift:190 (testDebug()) -> Event error(Error Domain=马小撂 Code=10086 "(null)")
Unhandled error happened: Error Domain=马小撂 Code=10086 "(null)"
 subscription called from:

2019-10-27 17:42:20.769: MErrorAndDebugViewController.swift:190 (testDebug()) -> isDisposed
next(apple) next(banana) next(Maxiaoliao) completed 
  • RxSwift.Resources.total

查看当前 资源数量。检查内存泄露

示例:

print(RxSwift.Resources.total)

let subject = BehaviorSubject(value: "Maxiaoliao")

let subscription1 = subject.subscribe(onNext: { print($0) })

print(RxSwift.Resources.total)

let subscription2 = subject.subscribe(onNext: { print($0) })

print(RxSwift.Resources.total)

subscription1.dispose()

print(RxSwift.Resources.total)

subscription2.dispose()

print(RxSwift.Resources.total)
输出:
2
Maxiaoliao
9
Maxiaoliao
12
10
8

调用RxSwift.Resources.total这个方法时候可能会报一个错误Module ‘RxSwift’ has no member named ‘Resources 解决方法:github.com/ReactiveX/R…podfile文件下添加代码

post_install do |installer|
   installer.pods_project.targets.each do |target|
      if target.name == 'RxSwift'
         target.build_configurations.each do |config|
            if config.name == 'Debug'
               config.build_settings['OTHER_SWIFT_FLAGS'] ||= ['-D', 'TRACE_RESOURCES']
            end
         end
      end
   end
end

运行成功