flapmap 操作符將源 Observable 的每一個元素應(yīng)用一個轉(zhuǎn)換方法吼虎,將他們轉(zhuǎn)換成 Observables号俐。 然后將這些 Observables 的元素合并之后再發(fā)送出來营勤。
func flapmap(){
let result = text_field.rx.text.orEmpty.flatMap {[weak self](text) ->Observable<Any> in
return (self?.requestMessage(str: text ))!.observeOn(MainScheduler.instance)
}.share()
result.subscribe(onNext: { (element) in
print("訂閱到:\(element)")
}).disposed(by: bag)
result.subscribe(onNext: {(element) in
print("訂閱到:\(element) - \(Thread.current)")
}).disposed(by: bag)
}
func requestMessage(str:String)->Observable<Any>{
print("開始請求")
return Observable.create { (observe) -> Disposable in
observe.onNext("發(fā)送信息")
return Disposables.create()
};
}
drive 是一個精心準(zhǔn)備的特征序列。它主要是為了簡化 UI 層的代碼盗蟆。有如下特征:
- 不會產(chǎn)生
error
事件 - 一定在
MainScheduler
監(jiān)聽(主線程監(jiān)聽) - 可以共享
func driveSs(){
let result = text_field.rx.text.orEmpty.asDriver()
let result1 = result.flatMap { [weak self](text) -> Driver<Any> in
return (self?.requestMessage(str: text))!.asDriver(onErrorJustReturn: "455")
}
result1.map{"come \($0)"}.drive(lab.rx.text).disposed(by: bag)
let _ret: BehaviorRelay<String> = BehaviorRelay(value: "")
var ret: Driver<String> {
return _ret.asDriver().distinctUntilChanged()
}
ret.asObservable().subscribe(onNext: { [weak self] dateRange in
print(dateRange)
}).disposed(by: bag)
result1.map{"comesss \($0)"}.drive(_ret).disposed(by: bag)
}
publish 會將 Observable
轉(zhuǎn)換為可被連接的 Observable
旧巾。可被連接的 Observable
和普通的 Observable
十分相似,不過在被訂閱后不會發(fā)出元素蜕劝,直到 操作符被應(yīng)用為止檀头。這樣一來你可以控制 Observable
在什么時候開始發(fā)出元素轰异。
func publish(){
let intSequence = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.publish()
_ = intSequence
.subscribe(onNext: { print("Subscription 1:, Event: \($0)") })
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
_ = intSequence.connect()
}
DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
_ = intSequence
.subscribe(onNext: { print("Subscription 2:, Event: \($0)") })
}
intSequence.connect().disposed(by: bag)
}
//打印結(jié)果
//Subscription 1:, Event: 0
//Subscription 1:, Event: 1
//Subscription 1:, Event: 2
//Subscription 1:, Event: 3
//Subscription 2:, Event: 3
//Subscription 1:, Event: 4
//Subscription 2:, Event: 4
//Subscription 1:, Event: 5
//Subscription 2:, Event: 5
combineLatest 將多個 Observables 中最新的元素通過一個函數(shù)組合起來,然后將這個組合的結(jié)果發(fā)出來暑始。
//會等first搭独,second都發(fā)出信號才會組合結(jié)果響應(yīng)出來
//打印結(jié)果 2A 2B
func combine(){
let first = PublishSubject<String>()
let second = PublishSubject<String>()
Observable.combineLatest(first, second){ $0 + $1}
.subscribe(onNext: { str in
print(str)
}).disposed(by: bag)
first.onNext("1")
first.onNext("2")
second.onNext("A")
second.onNext("B")
}