说明
再实际开发中,项目接入rxSwift时,难免会遇到一些封装的代码实用了代理,代理
很明显不符合rxSwift的链式编程,于是,需要对已有的代理进行处理。
这里需要建立一个中间代理,每次触发delegate时,都会先触发中间代理,然后中间
代理作为一个序列发送值给订阅者。
rxSwift给出的方案是DelegateProxy;而在rxCocoa中,也已经给出了一些Proxy:
* RxCollectionViewDataSourceProxy
* RxCollectionViewDelegateProxy
* RxScrollViewDelegateProxy
* RxSearchBarDelegateProxy
* RxTableViewDataSourceProxy
* RxTableViewDelegateProxy
* RxTextViewDelegateProxy
* RxTextStorageDelegateProxy
* RxImagePickerDelegateProxy
如何自定义Proxy
class RxxxxxDelegateProxy: DelegateProxy, jlxxxxDelegate, DelegateProxyType {
static func currentDelegateFor(object: AnyObject) -> AnyObject? {
let rxButton = object as! jlButton
return rxButton.delegagte
}
static func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) {
let rxButton = object as! jlButton
rxButton.delegate = delegate as? jlxxxxDelegate
}
}
其实就是要继承DelegateProxy和实现DelegateProxyType;
其中jlxxxxDelegate是要包装的delegate,要注意的是,jlxxxxDelegate中的方法要用@objc修饰,
然后给jlButton写一个extension
extension jlButton {
var rx_delegate: DelegateProxy {
return proxyForObject(RxDelegateButtonDelegateProxy.self, self)
}
var rx_tap: ControlEvent<Void> {
let source = rx_delegate.observe(
return ControlEvent(events: source)
}
}
需要注意的是,再使用rx_tap前,把delegate设置了。