How to subscribe on the value changed control event of a UISwitch Using Rxswift
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)
There are couple of ways to do that. But this one is how I usually do it: Try this out.
self.mySwitch.rx.isOn.subscribe { isOn in
print(isOn)
}.disposed(by: self.disposeBag)
I hope this helps.
EDIT:
Another would be subscribing to the value
rx property of the UISwitch
, like so:
mySwitch.rx.value.subscribe { (isOn) in
print(isOn)
}.disposed(by: self.disposeBag)
Now, as for your comment:
this worked for me thanks , but I preferred subscribing on the control event it self, not the value.
We could do this below, I'm not sure though if there's a better way than this. Since UISwitch
is a UIControl
object, you can subscribe to its .valueChanged
event, like so:
mySwitch.rx.controlEvent([.valueChanged]).subscribe { _ in
print("isOn? : \(mySwitch.isOn)")
}.disposed(by: self.disposeBag)
More info: https://developer.apple.com/documentation/uikit/uiswitch