这篇文章总结一下一些场景的序列:
controlEvent
1.在主线程监听
2.会共享附加作用
3.没有error事件
button.rx.controlEvent(.touchUpInside)
.subscribe { (reslut) in
print("点击")
}.disposed(by: disposeBag)
bind
1.绑定在给定 Scheduler 上执行(默认 MainScheduler)
2.若产生错误事件,在调试环境下将执行 fatalError,在发布环境下将打印错误信息
textField.rx.text.bind(to: label.rx.text)
Signal
1.在主线程监听
2.会共享附加作用
func search(input: String)-> Observable<String> {
return Observable<String>.create({ (observer) -> Disposable in
DispatchQueue.global().async {
...//假装在子线程进行了耗时的搜索
let result = "返回结果"
observer.onNext(result)
observer.onCompleted()
}
return Disposables.create()
})
}
func test() {
let result = inputTf.rx.changed
.flatMap { [weak self](text) -> Observable<Any> in
//flatMap映射成新序列
return self.search(input: text)
.observeOn(MainScheduler())) //主线程
.catchErrorJustReturn("发生错误") //处理error
}.share(replay: 1, scope: .whileConnected) //共享状态变化
result.bind(to: label.rx.text) //绑定
}
Driver
1.在主线程监听
2.会共享附加作用
3.相当于简化Signal
,Driver
会对新观察者重新发送上一个元素,而Signal
不会对新观察者重新发送上一个元素
func search(input: String)-> Observable<String> {
return Observable<String>.create({ (observer) -> Disposable in
DispatchQueue.global().async {
...//假装在子线程进行了耗时的搜索
let result = "返回结果"
observer.onNext(result)
observer.onCompleted()
}
return Disposables.create()
})
}
func test() {
func testWithDriver() {
let result = inputTf.rx.changed
.asDriver()
.flatMap {
return self.search(input: $0)
.asDriver(onErrorJustReturn: "发生错误")
}
result.drive(label.rx.text)
}
}
Single
1.只能发送一次响应或error事件
let single = Single<Any>.create { (observer) -> Disposable in
observer(.success("一次"))
return Disposables.create()
}
single.subscribe { (reslut) in
print("订阅到了")
}.disposed(by: disposeBag)
single.subscribe { (reslut) in
print("订阅不到")
}.disposed(by: disposeBag)
Completable
1.只能发送一次完成或error事件
let completable = Completable.create { (observer) -> Disposable in
observer(.completed)
//observer(.error(NSError.init(domain: "error", code: 888, userInfo: nil)))
return Disposables.create()
}
completable.subscribe {
print("完成")
} onError: { (error) in
print("错误")
}
completable.subscribe {
print("不再打印")
} onError: { (error) in
print("不再打印")
}
Maybe
1.只能发送一次响应,或者完成事件,或者error事件
let maybe = Maybe<Any>.create { (observer) -> Disposable in
observer(.success(""))
//observer(.completed)
//observer(.error(NSError.init(domain: "error", code: 888, userInfo: nil)))
return Disposables.create()
}
maybe.subscribe { (reslut) in
print("订阅到了")
}.disposed(by: disposeBag)
maybe.subscribe { (reslut) in
print("订阅不到")
}.disposed(by: disposeBag)