Reputation: 958
I have a UISwitch
that is hooked to to rx
. Whenever it's toggled an alertView
is displayed. If ok is chosen, some stuff will happen, but if cancel is pressed, nothing will happen, and the UISwitch
will remain in the same place, that is it's not toggled.
mySwitch.rx.controlEvent(.valueChanged).subscribe(onNext: { [weak self] _ in
guard let self = self else { return }
CustomAlertViewController.standardTwoButtonMessageAlert(title: self.mySwitch.isOn ? "Do you want to turn this on?" : "Do you want to turn this off?", msg: "hello", action: {
print("Doing stuff")
}, cancelAction: {
//SHOULD NOT TOGGLE
})?.present(animated: true, onView: UIApplication.topViewController())
}).disposed(by: disposeBag)
There is also the problem of the UISwitch
already having been toggled when I reach cancelAction
, meaning that it needs to be toggled back again. How do I toggle it back? And is there a way to prevent it from toggling at all so I can manage this manually inside the closures?
Upvotes: 2
Views: 443
Reputation: 33979
This question describes two causes (the user toggling the switch & the user tapping the cancel button) and three effects (presenting the alert, turning the switch off & "doing stuff".) Let's solve for each effect.
We present the alert when the toggle switch is turned on... Since we need the value emitted by the alert's buttons, this effect will also be a cause for some other effect. That means we use flatMap rather than subscribe:
let alertResult = settingSwitch.rx.isOn
.filter { $0 }
.map { _ in }
.flatMapFirst { [unowned self] in
self.present(alert(title: "Hello", message: "Are you sure?"), animated: true)
}
.share(replay: 1)
If the user taps the cancel button on the alert, then we need to turn the switch off.
alertResult
.filter { $0 == .cancel }
.map { _ in false }
.bind(to: settingSwitch.rx.isOn)
.disposed(by: disposeBag)
If the user taps the ok button on the alert, then we need to do stuff.
alertResult
.filter { $0 == .ok }
.map { _ in }
.subscribe(onNext: {
doStuff()
})
.disposed(by: disposeBag)
This all assumes that you don't mind the switch being in the on position while the alert is up. If you want to stop that from happening, you will need to put a button over the switch and make the switch just an effect, not a cause.
Upvotes: 0