我尝试将DifficultyViewDelegate的委托迁移到observable。这是我的DifficultyViewDelegate:
@objc protocol DifficultyViewDelegate: class {
func levelDidIncrease()
func levelDidDecrease()
}
我的难度观点:
weak var delegate: DifficultyViewDelegate?
@IBAction func decreaseLevel(_ sender: Any) {
delegate?.levelDidDecrease()
}
@IBAction func increaseLevel(_ sender: Any) {
delegate?.levelDidIncrease()
}
这是我的RxDifficultyViewDelegateProxy
class RxDifficultyViewDelegateProxy: DelegateProxy, DelegateProxyType {
static func currentDelegateFor(_ object: AnyObject) -> AnyObject? {
let difficultyView: DifficultyView = object as! DifficultyView
return difficultyView.delegate
}
static func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) {
let difficultyView: DifficultyView = object as! DifficultyView
difficultyView.delegate = delegate as? DifficultyViewDelegate
}
}
我还在我的DifficultyView上添加了一个扩展名:
extension DifficultyView {
public var rx_delegate: RxDifficultyViewDelegateProxy {
return RxDifficultyViewDelegateProxy.proxyForObject(RxDifficultyViewDelegateProxy.self)
}
public var rx_levelDidIncrease: Observable<Void> {
return rx_delegate.methodInvoked(#selector(DifficultyViewDelegate.levelDidIncrease)).map { _ in return }
}
}
但是,当我这样做时似乎:
difficultyView.rx_levelDidIncrease.asObservable().subscribe(onNext: {
print("did increase")
}).addDisposableTo(disposeBag)
从未打过电话。有人有指针吗?
答案 0 :(得分:1)
尝试使用PublishSubject
:
DifficultyView:
class DifficultyView: UIView {
var levelDidIncrease = PublishSubject<Void>()
var levelDidDecrease = PublishSubject<Void>()
@IBAction func decreaseLevel(_ sender: Any) {
levelDidDecrease.onNext()
}
@IBAction func increaseLevel(_ sender: Any) {
levelDidIncrease.onNext()
}
}
然后:
var difficultyView = DifficultyView()
difficultyView.levelDidDecrease.asObservable()
.subscribe(onNext: {
print("did decrease")
})
.addDisposableTo(disposeBag)
difficultyView.decreaseLevel(theSender) // <- THIS line performs the side effect