// This button has different images with for selection and no selection which I configured in storyboard different images for two states.
@IBOutlet weak var selectedRestarunt: UIButton!
// I am binding isSelected state like this which is working when user taps on button.
selectedRestarunt.rx.tap.scan(false) { lastState, _ in
return !lastState
}
现在我有一个案例我手动标记isSelected
而没有点击。
selectedRestarunt.isSelected = false/true
这不应该触发现有的映射。
这应该以某种方式映射,以便我需要基于isSelected
状态的某些操作。
谁能解释我怎样才能实现这个目标?
答案 0 :(得分:0)
您可以使用类似RxFeedback的架构:
...
let isSelected = PublishSubject<Bool>()
enum Event {
case setIsSelected(Bool)
case toggle
}
override func viewDidLoad() {
super.viewDidLoad()
Observable.merge(
isSelected.map { Event.setIsSelected($0) },
selectedRestarunt.rx.tap.map { _ in Event.toggle }
).scan(false) { lastState, event in
switch event {
case .setIsSelected(let selected):
return selected
case .toggle:
return !lastState
}
}.bind(to: selectedRestarunt.rx.isSelected)
.disposed(by: disposeBag)
isSelected.onNext(true) // Mark isSelected manually without tap.
}
...
使用Event
枚举来描述状态更改,然后使用scan
运算符应用更改。