简介
git地址: https://github.com/ReactiveX/RxSwift 参考资料:http://t.swift.gg/d/2-rxswift ReactiveX是通过可观察的流实现异步编程的一种API,它结合了观察者模式、迭代器模式和函数式编程的精华,RxSwift 是 ReactiveX 编程思想的一种实现。复制代码
retry
订阅失败了,再尝试重新订阅.比如网络请求失败,可以进行重新连接。
let disposeBag = DisposeBag()var count = 1 let retrySequence = Observable.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)结果:??Error encountered????复制代码
retry(_:)
跟retry相同,多了一个重试次数的参数
catchError
遇到错误时,返回一个新序列.
let disposeBag = DisposeBag() let sequenceThatFails = PublishSubject()let recoverySequence = PublishSubject () 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("?")结果:next(?)next(?)next(?)Error: testnext(?)复制代码
catchErrorJustReturn
遇到错误,就返回一个值.
let sequenceThatFails = PublishSubject ()_ = sequenceThatFails .catchErrorJustReturn(100) .subscribe { print($0)}sequenceThatFails.on(.Next(1))sequenceThatFails.on(.Next(2))sequenceThatFails.on(.Next(3))sequenceThatFails.on(.Error(NSError(domain: "Test", code: 0, userInfo: nil)))sequenceThatFails.on(.Next(4))复制代码
注
如有侵权,请告知删除.