01. AnyObserver
AnyObserver
可以用来描叙任意一种观察者;
可以通过Observable
来bind(to: observer)
,当Observable
发出元素的时候会执行AnyObserver
的回调;
func anyObserver() { let observable = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance) let observer = AnyObserver<String> {[weak self] (value) in if case .next(let text) = value { self?.label.text = text } } observable.map({ "倒计时: \($0)" }).bind(to: observer).disposed(by: disposeBag) }
02. Binder
Binder的特性
1. 不会处理错误事件,一旦产生错误事件,在调试环境下将执行fatalError
,在发布环境下将打印错误信息;
2. 确保绑定都是在给定 Scheduler
上执行(默认 MainScheduler
);
(1)直接创建,并绑定
func bindObserver() { let binder = Binder<String>(label) { (label, text) in label.text = text } let observable = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance) observable.map({ "倒计时: \($0)" }).bind(to: binder).disposed(by: disposeBag) }
(2)创建一个Binder
,将Observable
绑定到binder
,当发出错误事件的时候在调试环境下将执行fatalError
,在发布环境下将打印错误信息;
func bindError() { let binder = Binder<String>(label) { (label, text) in label.text = text } let observable = Observable<Int>.create { (observer) -> Disposable in observer.onError(TestError.none) return Disposables.create() } observable.map({ "倒计时: \($0)" }).bind(to: binder).disposed(by: disposeBag) }
运行结果:
Fatal error: Binding error: none: xxx
(3)给UI
控件扩展自定义的Binder
(实际开发中常用)
extension UILabel { var binderColor: Binder<UIColor> { Binder<UIColor>(self) { (label, textColor) in label.textColor = textColor } } }
调用
observable.map({ $0 % 2 == 0 ? .blue : .red }).bind(to: label.binderColor).disposed(by: disposeBag)
(4)给Rective
扩展自定义的Binder
,作为通用的Binder
(实际开发中常用)
extension Reactive where Base == UILabel { var binderFont: Binder<UIFont> { Binder<UIFont>(self.base) { (label, font) in label.font = font } } }
调用
observable.map({ .systemFont(ofSize: $0 % 2 == 0 ? 15 : 20)