7. RxSwift 訂閱操作過濾2 distinctUntilChanged、single、elementAt、ignoreElements、take、takeLast、skip、debounce
阿新 • • 發佈:2020-11-21
distinctUntilChanged
過濾連續重複的事件
let ob = Observable.of(1, 1, 1, 3, 5, 7, 9, 9)
ob.distinctUntilChanged().subscribe(onNext: { element in
print(element)
//1 3 5 7 9
}).disposed(by: disposeBag)
single
只發送一次正常事件,如果沒有或者超過 1 個會發送 error
事件
let ob = Observable.of(1,2) ob.single().subscribe(onNext: { element in print(element) }, onError: { error in print("錯誤",error) }).disposed(by: disposeBag) // 1 // 錯誤 Sequence contains more than one element. //----- single 增加過濾 let ob = Observable.of(1, 2, 1) ob.single { $0 == 2 }.subscribe(onNext: { element in print(element) }, onError: { error in print("錯誤", error) }).disposed(by: disposeBag) // 2
elementAt
獲取指定位置的事件,0 開始。 如果沒有發生該指定位置事件 會發送錯誤
let ob = Observable.of(0, 1, 2, 3, 4)
ob.elementAt(2).subscribe(onNext: { element in
print(element)
}, onError: { error in
print(error)
}).disposed(by: disposeBag)
//2
ignoreElements
會忽略所有主動傳送的event
事件,只保留 error
事件和 Completed
事件
let ob = Observable.of(0,1,2,3,4) ob.ignoreElements().subscribe { print("Completed") } onError: { (error) in print(error) }.disposed(by: disposeBag)
take
只取前 n 個事件,數量達到或不足會發送 Completed
。
let ob = Observable.of(0, 1, 2, 3)
ob.take(2).subscribe { element in
print(element)
} onError: { error in
print(error)
} onCompleted: {
print("onCompleted")
}.disposed(by: disposeBag)
takeLast
只取後 n 個事件,數量達到或不足會發送 Completed
。
let ob = Observable.of(0, 1, 2, 3, 4) ob.takeLast(12).subscribe { element in print(element) } onError: { error in print(error) } onCompleted: { print("onCompleted") }.disposed(by: disposeBag)
skip
跳過前 n 個事件,傳送完剩下的事件後會傳送onCompleted
。不足 n 個直接傳送onCompleted
。
let ob = Observable.of(0,1,2,3,4,5)
ob.skip(4).subscribe { (element) in
print(element)
} onError: { (error) in
print(error)
} onCompleted: {
print("onCompleted")
}.disposed(by: disposeBag)
debounce
當兩個事件的傳送間隔大於約定時間時才會收到該事件,常用的例子是搜尋時延遲搜尋
let ob = PublishSubject<String>()
ob.debounce(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).subscribe(onNext: { element in
print("收", element, CFAbsoluteTimeGetCurrent())
}).disposed(by: disposeBag)
print("發", "aaa", CFAbsoluteTimeGetCurrent())
ob.onNext("aaa")
DispatchQueue.global().asyncAfter(deadline: .now() + 0.5) {
print("發", "bbb", CFAbsoluteTimeGetCurrent())
ob.onNext("bbb")
}
DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {
print("發", "ccc", CFAbsoluteTimeGetCurrent())
ob.onNext("ccc")
}
DispatchQueue.global().asyncAfter(deadline: .now() + 3.5) {
print("發", "ddd", CFAbsoluteTimeGetCurrent())
ob.onNext("ddd")
}
//發 aaa 627481044.719082
//發 bbb 627481045.241852
//發 ccc 627481046.231139
//收 ccc 627481047.233378
//發 ddd 627481048.552644
//收 ddd 627481049.55595