2

I'm dealing with such case and I think of applying RxSwift here.

I have .xib UIView with button.

class RightButtonItemView: UIView {

    @IBOutlet weak var rightButtonimageView: UIImageView!
    @IBOutlet weak var rightButtonButton: UIButton!

    let performEventSegue = PublishSubject<Bool>()

    class func instanceFromNib() -> RightButtonItemView {
        return UINib(nibName: "NotificationView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as!  RightButtonItemView
    }

    override func awakeFromNib() {
       //I'm not sure how should I link button tap and my subject 
       rightButtonButton.rx.tap
    }
}

I create an instance of this view in my viewController

var rightButtonItemView = RightButtonItemView.instanceFromNib()

Bu clicking on this button from my segue I need to move to next VC, so I subscribing to UIView's subject

rightButtonItemView.performEventSegue.asObserver().subscribe(onNext: { (isAuthorized) in

        if isAuthorized {
            let storyboard = UIStoryboard(name: "Notifications", bundle: nil)
            let viewController = storyboard.instantiateViewController(withIdentifier: "UserNotificationsViewController")
            self.present(viewController, animated: true, completion: nil)
        }
    })

But I can't get how can I link button tap with changing state of my Publish Subject?

dand1
  • 371
  • 2
  • 8
  • 22

1 Answers1

5

You use the bind operator in this situation:

class RightButtonItemView: UIView {

    @IBOutlet weak var rightButtonimageView: UIImageView!
    @IBOutlet weak var rightButtonButton: UIButton!

    let performEventSegue = PublishSubject<Void>()
    private let bag = DisposeBag()

    class func instanceFromNib() -> RightButtonItemView {
        return UINib(nibName: "NotificationView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as!  RightButtonItemView
    }

    override func awakeFromNib() {
        rightButtonButton.rx.tap
            .bind(to: performEventSegue)
            .disposed(by: bag)
    }
}

-- UPDATE --

I thought of this solution and I think it's better. You don't need the Subject at all:

class RightButtonItemView: UIView {

    @IBOutlet weak var rightButtonButton: UIButton!

    var performEventSegue: Observable<Void> {
        return rightButtonButton.rx.tap.asObservable()
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72