(*useful)标记:目前觉得有用的函数
//FIXME 标记:待补充
Combination将多个源可观察对象合并为单个可观察对象
startWith:会在队列开始之前插入一个事件元素。
let disposeBag = DisposeBag()
Observable.of("🐶", "🐱", "🐭", "🐹")
.startWith("1️⃣")
.startWith("2️⃣")
.startWith("3️⃣", "🅰️")
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
打印:
3️⃣
🅰️
2️⃣
1️⃣
🐶
🐱
🐭
🐹
merge :(*useful)将多个可观察序列的元素组合成一个新的可观察序列
每个事件都会独立执行
let disposeBag = DisposeBag()
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.of(subject1, subject2)
.merge()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("🅰️")
subject1.onNext("🅱️")
subject2.onNext("①")
subject2.onNext("②")
subject1.onNext("🆎")
subject2.onNext("③")
打印:
🅰️
🅱️
①
②
🆎
③
zip:(*useful)先来后到(每个事件都会组合执行
合并N条队列,不过它会等到N个队列的元素一一对应地凑齐了之后再合并
zip
就像是拉链一样,两根拉链拉着拉着合并到了一根上:
let disposeBag = DisposeBag()
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.zip(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("🅰️")
stringSubject.onNext("🅱️")
stringSubject.onNext("🆎")
intSubject.onNext(3)
打印:
--- zip example ---
🅰️ 1
🅱️ 2
🆎 3
combineLatest:(*useful)只有一个位置(后来的会把前面的挤下去
只会把最新发出事件的Observable进行合并
let disposeBag = DisposeBag()
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.combineLatest(stringSubject, intSubject) { stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
stringSubject.onNext("🅰️")
stringSubject.onNext("🅱️")
intSubject.onNext(1)
intSubject.onNext(2)
stringSubject.onNext("🆎")
打印:
🅱️
1 //🅰️
消息被🅱️
挤下去了
🅱️
2
🆎 2
用集合数组来测试:(元素只能是同一种类型
let disposeBag = DisposeBag()
let stringObservable = Observable.just("❤️")
let fruitObservable = Observable.from(["🍎", "🍐", "🍊"])
let animalObservable = Observable.of("🐶", "🐱", "🐭", "🐹")
Observable.combineLatest([stringObservable, fruitObservable, animalObservable]) {
"\($0[0]) \($0[1]) \($0[2])"
}
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
//FIXME :不理解这是怎么回事
// 每个序列的元素按顺序执行,就能理解了
打印:
❤️ 🍎 🐶 //都执行的第一个element
❤️ 🍐 🐶 //按顺序执行到 form的第二个元素🍐,把🍎挤下去了
❤️ 🍐 🐱 //按顺序执行到 of的第二个元素🐱, 把🐶挤下去了
❤️ 🍊 🐱 //按顺序执行到 from的第三个元素🍊, 把🍐挤下去了
❤️ 🍊 🐭 //按顺序执行到 of的第三个元素🐭, 把🐱挤下去了
❤️ 🍊 🐹 //按顺序执行到 of的第四个元素🐹, 把🐭挤下去了
switchLatest:(*useful)
获取信号中信号最近发出信号,订阅最近发出的信号
如果有多个信号事件(sendNext)从流水线流出来,那么只接收最新的信号事件。
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "⚽️")
let subject2 = BehaviorSubject(value: "🍎")
let variable = Variable(subject1)
variable.asObservable()
.switchLatest()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("🏈")
subject1.onNext("🏀")
variable.value = subject2
subject1.onNext("⚾️")
subject2.onNext("🍐")
打印:
⚽️ // 当前为subject1
🏈
🏀
🍎 // 当前为subject2 --> subject1的⚾️并未输出
🍐