let dispose = DisposeBag()
just()
- 通过传入默认值初始化,Observable泛型,指定类型和不指定类型都无所谓,swift会自动推断类型被订阅之后,会一次性输出事件的全部内容
let justFunc = Observable.just(1)
// let justFunc = Observable.just([1, 2, 3, 4])
// let justFunc = Observable.just("string")
// let justFunc = Observable.just(["abc", 1, ["a", "b"], ["key1" : "value1", "key2" : "value2"]])
justFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
of()
- 通过传入默认值初始化,Observable泛型,指定类型和不指定类型都无所谓,swift会自动推断类型,但是类型必须相同被订阅之后,会逐个输出事件的内容
let ofFunc = Observable.of(1, 2, 3, 4, 5, 6)
// let ofFunc = Observable.of([1, 2, 3, 4, 5, 6], [1, 2, 3, 4], [4, 5, 6])
ofFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
from()
- 通过传入默认值初始化,且必须是数组类型,被订阅之后,事件中数组的内容会逐个输出
let fromFunc = Observable.from([1, 2, 3, 4, 5, 6])
// let fromFunc = Observable.from([1, 2, "3", 4, 5, 6])
fromFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
empty()
let emptyFunc = Observable.empty()
never()
let neverFunc = Observable.never()
error()
- 创建一个发送错误error的Observable,Error是个enum类型
let errorFunc = Observable.error(NSError(domain: "local", code: 0, userInfo: nil))
range()
- 创建一个以start值为起始,count值为个数的Observable,且start的值和count的值必须为integer
let rangeFunc = Observable.range(start: 1, count: 9)
rangeFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
repeatElement()
- 通过传入默认值初始化,创建一个以默认值为准的无线发送事件的Observable
let repeatElementFunc = Observable.repeatElement(1)
repeatElementFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
generate()
- 创建一个通过传入初始值,在满足条件下循环执行的Observable
let generateFunc = Observable.generate(initialState: 2, condition: {
$0 <= 10
}, iterate: {
$0 + 2
})
generateFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
create()
let observable = Observable.create{observer in
//对订阅者发出了.next事件,且携带了一个数据"hangge.com"
observer.onNext("hangge.com")
//对订阅者发出了.completed事件
observer.onCompleted()
//因为一个订阅行为会有一个Disposable类型的返回值,所以在结尾一定要returen一个Disposable
return Disposables.create()
}
//订阅测试
observable.subscribe {
print($0)
}.disposed(by: dispose)
deferred()
- 创建一个输出Observable的Observable
let deferredFunc = Observable.deferred {
return Observable.of(1)
}
deferredFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
interval()
- 创建一个在主线程(MainScheduler.instance)中,没隔一定的时间发送一个事件的Observable
let intervalFunc = Observable.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
intervalFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
timer()
- 有两个API
- 第一种:创建一个在指定时间后,发送一次事件的Observable
let timerFunc = Observable.timer(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
timerFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
- 第二种:创建一个在指定时间后,每隔一个指定的时间发送一次事件的Observable
let timerFunc = Observable.timer(RxTimeInterval.seconds(1), period: RxTimeInterval.seconds(2), scheduler: MainScheduler.instance)
timerFunc.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
buffer()
- 在指定的线程(scheduler)中,设置一个时间段(timeSpan),缓存指定个数(count)的事件。
- 在该时间段内,如果缓存个数提前达到要求,则立即以集合的形式发送出去;如果该时间段内没有达到缓存个数要求,时间一到也立即把已经缓存到的事件以集合的形式发送出去。
let subject = PublishSubject()
subject.buffer(timeSpan: RxTimeInterval.seconds(2), count: 3, scheduler: MainScheduler.instance).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
subject.onNext("1")
subject.onNext("2")
subject.onNext("3")
subject.onNext("4")
subject.onNext("5")
subject.onNext("6")
subject.onNext("7")
subject.onNext("8")
subject.onNext("9")
window()
- 在指定的线程(scheduler)中,设置一个时间段(timeSpan),缓存指定个数(count)的Observable。
- 在该时间段内,实时的将缓存到的Observable发送出去。
let subject = PublishSubject()
subject.window(timeSpan: RxTimeInterval.seconds(2), count: 3, scheduler: MainScheduler.instance).subscribe(onNext: { (content) in
print("content = \(content)")
content.subscribe { (event) in
print("event = \(event)")
}.disposed(by: self.dispose)
}).disposed(by: dispose)
subject.onNext("1")
subject.onNext("2")
subject.onNext("3")
subject.onNext("4")
subject.onNext("5")
subject.onNext("6")
subject.onNext("7")
subject.onNext("8")
map()
- 将Observable的每个元素通过一个函数转换成一个新的Observable。
// RxSwift的map
let array = Observable.of(1, 2, 3, 4, 5)
array.map { item in
item * 10
}.subscribe { (item) in
print("item = \(item)")
}.disposed(by: dispose)
// 系统的map
let sysArrayMap = [1, 2, 3, 4, 5].map { item in
item * 10
}
print(sysArrayMap)
flatMap()
- 将所有的Observable的每个元素压缩成一个Observable,再逐一发送出来。
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "A")
let subject2 = BehaviorSubject(value: "1")
let subject3 = BehaviorSubject(value: "a1")
let relay = BehaviorRelay(value: subject1)
relay.flatMap {
$0
}.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: disposeBag)
subject1.onNext("B")
relay.accept(subject2)
subject2.onNext("2")
subject1.onNext("C")
relay.accept(subject3)
subject3.onNext("b2")
subject3.onNext("c3")
subject2.onNext("3")
subject1.onNext("D")
flatMapLatest()
- 和flatMap用法相同,区别是只会处理最后一个赋值的Observable,之前赋值过的Observable再发送事件不会被接收。
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "A")
let subject2 = BehaviorSubject(value: "1")
let subject3 = BehaviorSubject(value: "a1")
let relay = BehaviorRelay(value: subject1)
relay.flatMapLatest {
$0
}.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: disposeBag)
subject1.onNext("B")
relay.accept(subject2)
subject2.onNext("2")
subject1.onNext("C")
relay.accept(subject3)
subject3.onNext("b2")
subject3.onNext("c3")
// subject2和subject1的事件不会被接收
subject2.onNext("3")
subject1.onNext("D")
subject3.onNext("d4")
flatMapFirst()
- 只会处理第一个赋值的Observable,后面所有再被赋值的Observable一律你接收。
scan()
- 初始化时指定一个值,遍历整个Observable,将所有参数通过一个函数逐一处理一遍,最后的结果再和初始值通过该函数处理。
let obser = Observable.of(1, 3, 5, 7, 9)
obser.scan(2) { a,b in
a * b
}.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
groupBy()
- 将原Observable中的元素,按照指定的规则分成多个子Observable发送出来。
let obser = Observable.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
obser.groupBy { (index) -> String in
return index % 2 == 0 ? "偶数" : "奇数"
}
.subscribe { (event) in
// print("event = \(event)")
let key: String = event.element?.key ?? ""
event.element?.subscribe(onNext: { (content) in
print("key = \(String(describing: key)) content = \(content)")
}).disposed(by: self.dispose)
}.disposed(by: dispose)
filter()
- 将Observable中的元素,按照指定的条件发送出来。
let obser = Observable.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
obser.filter { index in
index > 5
}.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
// 系统方法
let array = [1, 2, 3, 4, 5]
let result = array.filter { index in
index > 3
}
print(result)
distinctUntilChanged()
let obser = Observable.of(1, 2, 1, 2, 3, 4, 1, 2, 1, 1, 1, 5)
obser.distinctUntilChanged().subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
single()
- 筛选出Observable中符合条件的第一个元素并输出,如果满足条件的元素大于1或者Observable中元素没有满足条件的,将输出一个error。
let obser = Observable.of(1, 2, 1, 2, 3, 4, 1, 2, 1, 1, 1, 5)
obser.single { item in
item == 2
}.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
elementAt()
- 创建时需要一个默认值,只输出Observable中指定位置的事件。
let obser = Observable.of(1, 2, 1, 2, 3, 4, 1, 2, 1, 1, 1, 5)
obser.elementAt(2).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
ignoreElements()
- 获取Observable事件输出completed的状态。
let obser = Observable.of(1, 2, 1, 2, 3, 4, 1, 2, 1, 1, 1, 5)
obser.ignoreElements().subscribe({ (content) in
print("content = \(content)")
}).disposed(by: dispose)
take()
- 创建时需要一个默认值n,只输出Observable前n个事件,然后自动completed。
let obser = Observable.of(1, 2, 1, 2, 3, 4, 1, 2, 1, 1, 1, 5)
obser.take(4).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
takeLast()
- 和take()相反,只输出Observable后n个事件。
skip()
- 和take()类似,跳过Observable中前n个事件,然后再逐一发送剩余的事件。
sample()
- 让ObservableA监听另一个ObservableB,当被监听的ObservableB有事件发出(不包括error),ObservableA将发出最新产生的事件。
let source = PublishSubject()
let notifier = PublishSubject()
source
.sample(notifier)
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
source.onNext(1)
//让源序列接收接收消息
notifier.onNext("A")
source.onNext(2)
//让源序列接收接收消息
notifier.onNext("B")
notifier.onNext("C")
source.onNext(3)
source.onNext(4)
//让源序列接收接收消息
notifier.onNext("D")
// notifier.onError(NSError(domain: "local", code: 0, userInfo: nil))
source.onNext(5)
//让源序列接收接收消息
notifier.onCompleted()
debounce()
- 在指定时间间隔内只输出Observable高频产生的最后一个时间。
let times = [
[ "value": 1, "time": 0.1 ],
[ "value": 2, "time": 1.1 ],
[ "value": 3, "time": 1.2 ],
[ "value": 4, "time": 1.2 ],
[ "value": 5, "time": 1.4 ],
[ "value": 6, "time": 2.1 ]
]
//生成对应的 Observable 序列并订阅
Observable.from(times)
.flatMap { item in
return Observable.of(Int(item["value"]!))
.delaySubscription(RxTimeInterval.seconds(Int(item["time"]!)), scheduler: MainScheduler.instance)
}
.debounce(RxTimeInterval.seconds(Int(0.5)), scheduler: MainScheduler.instance)
.subscribe(onNext: { (content) in
print("content = \(content)")
})
.disposed(by: dispose)
amb()
- 同时监听多个Observable,只输出第一个产生事件的Observable,剩余其他的Observable忽略。
let subject1 = PublishSubject()
let subject2 = PublishSubject()
let subject3 = PublishSubject()
subject1
.amb(subject2)
.amb(subject3)
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
subject2.onNext(1)
subject1.onNext(20)
subject2.onNext(2)
subject1.onNext(40)
subject3.onNext(0)
subject2.onNext(3)
subject1.onNext(60)
subject3.onNext(0)
subject3.onNext(0)
takeWhile()
- 根据条件,输出Observable陆续产生的满足条件的事件。
let obser = Observable.of(1, 2, 3, 4, 5, 6)
obser.takeWhile { item in
item < 4
}.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
takeUntil()
- 让ObservableA监听另一个ObservableB,ObservableA持续发出事件,当被监听的ObservableB有事件发出,ObservableA将自动执行completed。
let source = PublishSubject()
let notifier = PublishSubject()
source
.takeUntil(notifier)
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
source.onNext("a")
source.onNext("b")
source.onNext("c")
source.onNext("d")
//source停止接收消息
notifier.onNext("z")
source.onNext("e")
source.onNext("f")
source.onNext("g")
skipWhile()
- 输出Observable中,不满足条件的所有事件。
let obser = Observable.of(2, 3, 4, 5, 6)
obser.skipWhile { $0 < 4 }
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
skipUntil()
- 和takeUntil()类似,让ObservableA监听另一个ObservableB,ObservableA持续发出事件,但是全部被忽略,不被接收,当被监听的ObservableB有事件发出,ObservableA发出的事件才会被接收。
let source = PublishSubject()
let notifier = PublishSubject()
source
.skipUntil(notifier)
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
source.onNext(1)
source.onNext(2)
source.onNext(3)
source.onNext(4)
source.onNext(5)
//开始接收消息
notifier.onNext(0)
source.onNext(6)
source.onNext(7)
source.onNext(8)
//仍然接收消息
notifier.onNext(0)
source.onNext(9)
startWith()
- 创建需要传入默认值,在预先知道Observable元素类型的前提下,提前对Observable插入一些默认值,当Observable有事件输出时,会先输出默认值。
let obser = Observable.of(1, 2, 3, 4, 5)
obser.startWith(99, 88, 77).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
merge()
- 合并两个及以上的Observable,合成一个新的Observable,并输出所有事件。
let subject1 = PublishSubject()
let subject2 = PublishSubject()
let obser = Observable.of(subject1, subject2)
obser.merge().subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
subject1.onNext(20)
subject1.onNext(40)
subject1.onNext(60)
subject2.onNext(1)
subject1.onNext(80)
subject1.onNext(100)
subject2.onNext(1)
zip()
- 合并两个及以上的Observable,合成一个新的Observable,并会自动合成一个元祖,且以最小count数的Observable的元素个数为准组合完成后再发出事件。
let subject1 = PublishSubject()
let subject2 = PublishSubject()
let subject3 = PublishSubject()
let obser = Observable.zip(subject1, subject2, subject3)
obser.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
subject1.onNext(20)
subject3.onNext("40")
subject1.onNext(60)
subject2.onNext(1)
subject1.onNext(80)
subject1.onNext(100)
subject2.onNext(1)
subject3.onNext("abc")
combineLatest()
- 合并两个及以上的Observable,合成一个新的Observable,并会自动合成一个元祖,与zip不同的是,combineLatest会以"先到先组合"的规则将最新产生的元素合成并输出。
let subject1 = PublishSubject()
let subject2 = PublishSubject()
let subject3 = PublishSubject()
let obser = Observable.combineLatest(subject1, subject2, subject3)
obser.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
subject1.onNext(20)
subject3.onNext("40")
subject1.onNext(60)
subject2.onNext(1)
subject1.onNext(80)
subject1.onNext(100)
subject2.onNext(1)
subject3.onNext("abc")
withLatestFrom()
- ObservableA依赖ObservableB,当ObservableA自身有元素产生的时候,会输出ObservableB产生的最新的元素。
let subject1 = PublishSubject()
let subject2 = PublishSubject()
subject1.withLatestFrom(subject2).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
subject1.onNext(20)
subject1.onNext(60)
subject2.onNext("Aa")
subject1.onNext(80)
subject2.onNext("Bb")
subject1.onNext(90)
subject1.onNext(10)
switchLatest()
- 切换监听对象,切换后前一个被监听的Observable所有产生事件将不会被接收。
let subject1 = BehaviorSubject(value: "A")
let subject2 = BehaviorSubject(value: "1")
let replay = BehaviorRelay(value: subject1)
replay.asObservable()
.switchLatest()
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
subject1.onNext("B")
subject1.onNext("C")
//改变事件源
replay.accept(subject2)
subject1.onNext("D")
subject2.onNext("2")
//改变事件源
replay.accept(subject1)
subject2.onNext("3")
subject1.onNext("E")
toArray()
- 将Observable中的所有元素整合成一个单一的事件并发送。
let obser = Observable.of(1, 2, 3, 4, 5)
obser.toArray().subscribe { (content) in
print("content = \(content)")
}.disposed(by: dispose)
reduce()
- 创建时设置一个默认值,和一个运算符,将Observable中的所有元素用给定的运算符逐渐操作,最后结果再与默认值进行操作,输出最后的事件。
let obser = Observable.of(1, 2, 3, 4, 5)
obser.reduce(2, accumulator: *).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
concat()
- 串联多个Observable,并在前一个Observable发送completed之后输出后一个Observable在赋值之后的所有的事件。
let sub1 = BehaviorSubject(value: 1)
let sub2 = BehaviorSubject(value: 2)
let relay = BehaviorRelay(value: sub1)
relay.asObservable().concat().subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
sub1.onNext(1)
sub1.onNext(1)
sub2.onNext(2)
// 重新赋值
relay.accept(sub2)
sub2.onNext(3)
sub1.onCompleted()
sub2.onNext(4)
sub2.onNext(5)
sub2.onNext(6)
publish()和connect()
- publish()是将一个普通的Observable转换成一个可连接的Observable,一个可连接的Observable才能被connect(),一个可连接的Observable在被订阅之后不会立即发送事件,只有调用了connect()之后才会发送事件。
let interval = Observable.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).publish()
//第一个订阅者(立刻开始订阅)
_ = interval
.subscribe(onNext: { print("订阅1: \($0)") })
// 开始连接
interval.connect().disposed(by: dispose)
//第二个订阅者(延迟5秒开始订阅)
delay(5) {
_ = interval
.subscribe(onNext: { print("订阅22222: \($0)") })
}
func delay(_ delay: Double, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
replay()
- replay()和publish()相同都是将一个普通的Observable转换成一个可连接的Observable,不同的是replay()创建需要一个默认值n,用于订阅后接收前一个Observable的最近的n个事件。
let interval = Observable.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).replay(2)
//第一个订阅者(立刻开始订阅)
_ = interval
.subscribe(onNext: { print("订阅1: \($0)") })
// 开始连接
interval.connect().disposed(by: dispose)
//第二个订阅者(延迟5秒开始订阅)
delay(5) {
_ = interval
.subscribe(onNext: { print("订阅22222: \($0)") })
}
func delay(_ delay: Double, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
multicast()
- multicast()和publish()相同都是将一个普通的Observable转换成一个可连接的Observable,不同的是multicast()可以传入一个subject,当Observable被订阅之后,subject会跟着发送自己的事件。
func someFuncTest() {
//每隔1秒钟发送1个事件
let subject = PublishSubject()
subject.subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
let interval = Observable.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).multicast(subject)
//第一个订阅者(立刻开始订阅)
_ = interval
.subscribe(onNext: { print("订阅1: \($0)") })
// 开始连接
interval.connect().disposed(by: dispose)
//第二个订阅者(延迟5秒开始订阅)
delay(5) {
_ = interval
.subscribe(onNext: { print("订阅22222: \($0)") })
}
}
func delay(_ delay: Double, closure: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
refCount()
- 将一个可连接的Observable转换成一个普通的Observable。
//每隔1秒钟发送1个事件
let interval = Observable.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).publish().refCount()
//第一个订阅者(立刻开始订阅)
_ = interval
.subscribe(onNext: { print("订阅1: \($0)") })
//第二个订阅者(延迟5秒开始订阅)
delay(5) {
_ = interval
.subscribe(onNext: { print("订阅22222: \($0)") })
}
share()
- share创建需要一个默认值n,共享Observable的事件,并从前一个订阅者的最近的n个事件开始发送事件。
//每隔1秒钟发送1个事件
let interval = Observable.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).share(replay: 1)
//第一个订阅者(立刻开始订阅)
_ = interval
.subscribe(onNext: { print("订阅1: \($0)") })
//第二个订阅者(延迟5秒开始订阅)
delay(5) {
_ = interval
.subscribe(onNext: { print("订阅22222: \($0)") })
}
//第三个订阅者
delay(8) {
_ = interval.subscribe(onNext: { (content) in
print("content = \(content)")
})
}
delay()
- 创建时需要一个默认时间值n,当Observable被订阅后,Observable所有产生的事件将在延迟时间后发送。
let obser = Observable.of(1, 2, 3, 4, 5, 6)
obser.delay(RxTimeInterval.seconds(3), scheduler: MainScheduler.instance).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
delaySubscription()
- 创建时需要一个默认时间值n,当经过该延迟时间后,Observable才会被订阅。
let obser = Observable.of(1, 2, 3, 4, 5, 6)
obser.delaySubscription(RxTimeInterval.seconds(3), scheduler: MainScheduler.instance).subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
materialize()
- 将Observable的事件转化成元素,再发送出去。
let obser = Observable.of(1, 2, 3, 4, 5, 6)
obser.materialize().subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
dematerialize()
- 和materialize()相反,将元素还原回事件,再发送出去。
timeout()
- 创建时设置一个默认的超时时间,当Observable在超时时间内没有元素发出将会产生一个超时的error事件。
//定义好每个事件里的值以及发送的时间
let times = [
[ "value": 1, "time": 0 ],
[ "value": 2, "time": 0.5 ],
[ "value": 3, "time": 1.5 ],
[ "value": 4, "time": 4 ],
[ "value": 5, "time": 5 ]
]
//生成对应的 Observable 序列并订阅
Observable.from(times)
.flatMap { item in
return Observable.of(Int(item["value"]!))
.delaySubscription(RxTimeInterval.seconds(Int(item["time"]!)),
scheduler: MainScheduler.instance)
}
.timeout(RxTimeInterval.seconds(2), scheduler: MainScheduler.instance) //超过两秒没发出元素,则产生error事件
.subscribe(onNext: { element in
print(element)
}, onError: { error in
print(error)
})
.disposed(by: dispose)
catchErrorJustReturn()
let sequenceThatFails = PublishSubject()
sequenceThatFails
.catchErrorJustReturn("错误")
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
sequenceThatFails.onNext("a")
sequenceThatFails.onNext("b")
sequenceThatFails.onNext("c")
sequenceThatFails.onError(MyError.A)
sequenceThatFails.onNext("d")
catchError()
- 捕获Observable发出的error事件,并返回一个Observable。
let sequenceThatFails = PublishSubject()
let recoverySequence = Observable.of("1", "2", "3")
sequenceThatFails
.catchError {
print("Error:", $0)
return recoverySequence
}
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
sequenceThatFails.onNext("a")
sequenceThatFails.onNext("b")
sequenceThatFails.onNext("c")
sequenceThatFails.onError(MyError.A)
sequenceThatFails.onNext("d")
retry()
- 创建时需要传入一个默认值n,表示重试次数,不设置默认一次。
var count = 1
let sequenceThatErrors = Observable.create { observer in
observer.onNext("a")
observer.onNext("b")
//让第一个订阅时发生错误
if count == 1 {
observer.onError(MyError.A)
print("Error encountered")
count += 1
}
observer.onNext("c")
observer.onNext("d")
observer.onCompleted()
return Disposables.create()
}
sequenceThatErrors
.retry(2) //重试2次(参数为空则只重试一次)
.subscribe(onNext: { print($0) })
.disposed(by: dispose)
debug()
- 创建时可以传入一个标记值,也可以传空,用于打印事件输出时的信息。
let obser = Observable.of(1, 2, 3, 4, 5, 6, 7)
obser.startWith(0, 0, 0).debug().subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
single()
- 只发出Observable产生的一个元素并发出一个error事件,如果Observable的元素大于1或没有元素,single将发出一个error事件。
let obser = Observable.of(1, 2)
obser.single().subscribe(onNext: { (content) in
print("content = \(content)")
}).disposed(by: dispose)
asSingle()
- 将一个普通的Observable转化成single类型,如果Observable只有一个元素,只发出钙元素,如果Observable的元素大于1或没有元素,single将发出一个error事件。
let obser = Observable.of(1)
obser.asSingle().subscribe({ (content) in
print("content = \(content)")
}).disposed(by: dispose)