今天谈一下RxSwift中的组合操作,和RAC一样。可以参照RAC理解。
Combination Operators在RxSwift中的实现有五种:
- startWith
- merge
- zip
- combineLatest
- switchLatest
StartWith
在Observable释放元素之前,发射指定的元素序列
StartWith.png
let disposeBag = DisposeBag()
Observable.of(["1","2","3"]).startWith(["0"]).subscribe({ (event) in
print(event)
}).disposed(by: disposeBag)
执行结果如下:
next(["0"])
next(["1", "2", "3"])
completed
Merge
将多个Observable组合成单个Observable,并且按照时间顺序发射对应事件
Merge.png 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,当有事件到达时,会在每个序列中对应的索引上对应的元素发出。
zip.png 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
combineLatest.png当一个项目由两个Observables发射时,通过一个指定的功能将每个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 = Variable(subject1)
variable.asObservable()
.switchLatest()
.subscribe(onNext: { print($0) })
.disposed(by: disposeBag)
subject1.onNext("2")
subject1.onNext("3")
variable.value = subject2
subject1.onNext("4")
subject2.onNext("B")
执行结果:
1
2
3
A
B
网友评论