How to subscribe on the value changed control event of a UISwitch Using Rxswift

MhmdRizk picture MhmdRizk · Nov 19, 2018 · Viewed 8k times · Source

I want to use Rxswift and not IBActions to solve my issue below,

I have a UISwitch and I want to subscribe to the value changed event in it,

I usually subscribe on Buttons using this manner

@IBOutlet weak var myButton: UIButton!


myButton
    .rx
    .tapGesture()
    .when(.recognized)
    .subscribe(onNext : {_ in /*do action here */})

Does anyone know how to subscribe to UISwitch control events?

Answer

MhmdRizk picture MhmdRizk · Nov 20, 2018

I found the answer Im looking for, in order to subscribe on and control event we should do the below :

@IBOutlet weak var mySwitch : UISwitch!

       mySwitch 
            .rx
            .controlEvent(.valueChanged)
            .withLatestFrom(mySwitch.rx.value)
            .subscribe(onNext : { bool in
                // this is the value of mySwitch
            })
            .disposed(by: disposeBag)