combineLatest
- 將多個
Observables
中最新的元素透過一個函數組合起來,然後將結果發出來。
let disposeBag = DisposeBag()
let first = PublishSubject<String>()
let second = PublishSubject<String>()
Observable.combineLatest(first, second) { $0 + $1 }
.dubscribe(onNext: { print($0) })
.disposed(by: disposeBag)
first.onNext("1")
second.onNext("A")
first.onNext("2")
second.onNext("B")
second.onNext("C")
second.onNext("D")
first.onNext("3")
first.onNext("4")
印出結果
1A
2A
2B
2C
2D
3D
4D
skip
- 跳過
Observable
中頭n
個元素
do
- 使用
do
來監聽事件的生命週期,它會在每一次事件發送前被調用。 - 它和
subscribe
一樣,可以通過不同的閉包回調不同類型的事件。 如:do(onNext: )
在subscribe(onNext:)
前,do(onCompleted:)
在subscribe(onCompleted:)
前調用。
let observable = Observable.of("A", "B", "C")
observable
.do(onNext: { element in
print("Intercepted Next:", element)
}, onError: { error in
print("Intercepted Error:", error)
}, onCompleted: {
print("Intercepted Completed")
}, onDispose: {
print("Intercepted Disposed")
})
.subscribe(onNext: { element in
print(element)
}, onError: { error in
print(error)
}, onCompleted: {
print("completed")
}, onDisposed: {
print("disposed")
})
印出結果
Intercepted Next: A
A
Intercepted Next: B
B
Intercepted Next: C
C
Intercepted Completed
completed
disposed
Intercepted Disposed