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?
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With