Cannot receive event with custom DelegateProxy and

2020-05-04 10:58发布

I try to migrate delegate of DifficultyViewDelegate to observable. This is my DifficultyViewDelegate :

@objc protocol DifficultyViewDelegate: class {
  func levelDidIncrease()
  func levelDidDecrease()
}

And my DifficultyView :

  weak var delegate: DifficultyViewDelegate?

  @IBAction func decreaseLevel(_ sender: Any) {
    delegate?.levelDidDecrease()
  }

  @IBAction func increaseLevel(_ sender: Any) {
    delegate?.levelDidIncrease()
  }

And this is my 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
  }
}

I also added an extension on my 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 }
  }
}

But it seems that when I do :

difficultyView.rx_levelDidIncrease.asObservable().subscribe(onNext: {
  print("did increase")
}).addDisposableTo(disposeBag)

It's never called. Someone has any pointers ?

1条回答
女痞
2楼-- · 2020-05-04 11:51

Try use 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()
   }
}

And then:

var difficultyView = DifficultyView()

difficultyView.levelDidDecrease.asObservable()
    .subscribe(onNext: {
        print("did decrease")
    })
    .addDisposableTo(disposeBag)


difficultyView.decreaseLevel(theSender) // <- THIS line performs the side effect
查看更多
登录 后发表回答