RxSwift Combining Observables
2020-09-27 本文已影响0人
迷路的小小
startWith
在Observabl
e释放元素之前,发射指定的元素序列。
let disposeBag = DisposeBag()
Observable.of(["C","C++","OC"]).startWith(["先吃饱饭再学习"]).subscribe({ (event) in
print(event)
}).disposed(by: disposeBag)
"先吃饱饭再学习","C", "C++", "OC"
merge
将多个Observable
组合成单个Observable
,并且按照时间顺序发射对应事件。
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
将多个Observable
(注意:必须是要成对
)组合成单个Observable
,当有事件到达时,会在每个序列中对应的索引上对应的元素发出。(ps:之前版本的RxSwift好像最多只能组合8个Observable
)
let disposeBag = DisposeBag()
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.zip(subject1, subject2) { string1,string2 in
"\(string1)--\(string2)"
}.subscribe(onNext: {print($0)}).disposed(by: disposeBag)
subject1.onNext("A")
subject1.onNext("B")
subject1.onNext("C")
subject2.onNext("1")
subject2.onNext("2")
// A--1, B--2
combineLatest
当一个项目由两个Observable
发射时,通过一个指定的功能将每个Observable
观察到的最新项目组合起来,并根据该功能的结果发射事件。
let disposeBag = DisposeBag()
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.combineLatest(subject1, subject2) { string1,string2 in
"\(string1)--\(string2)"
}.subscribe(onNext: {print($0)}).disposed(by: disposeBag)
subject1.onNext("A")
subject2.onNext("1")
subject2.onNext("2")
subject1.onNext("B")
subject1.onNext("C")
// A--1, A--2, B--2, C--2
switchLatest
切换Observable
队列。
let disposeBag = DisposeBag()
let subject1 = BehaviorSubject(value: "1")
let subject2 = BehaviorSubject(value: "A")
let variable = BehaviorRelay(value: subject1)
variable.asObservable()
.switchLatest()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("2")
subject1.onNext("3")
variable.accept(subject2)
subject1.onNext("4")
subject2.onNext("B")
打印结果:1,2,3,A,B