Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 256
MhmdRizk Avatar asked Nov 19 '18 19:11

MhmdRizk


2 Answers

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)
like image 149
MhmdRizk Avatar answered Jan 04 '23 12:01

MhmdRizk


Below are some caveats you would use for UISwitch:

 1. Make sure the event subscribes to unique changes so use distinctUntilChanged
 2. Rigorous switching the switch can cause unexpected behavior so use debounce.

 Example: 

anySwitch.rx
.isOn.changed //when state changed
.debounce(0.8, scheduler: MainScheduler.instance) //handle rigorous user switching
.distinctUntilChanged().asObservable() //take signal if state is different than before. This is optional depends on your use case
.subscribe(onNext:{[weak self] value in
            //your code
}).disposed(by: disposeBag)
like image 27
prex Avatar answered Jan 04 '23 12:01

prex