I'm trying to add a switch change state action to each tableview cell on my tableview, The problem is that the first time I run the application the state action gets called for each cell created. Has an example when I initially have 5 items on the database, the first time I load the tableview the switch will be called 5 times. What I want is an action function, outside the binding, to be called ONLY when the user has clicked the switch.
Here is the code for the tableview cell:
class SensorCell: UITableViewCell {
@IBOutlet weak var txtIndex: UILabel!
@IBOutlet weak var txtSensorItem: UILabel!
@IBOutlet weak var sensorSwitch: UISwitch!
var cellBag = DisposeBag()
override func awakeFromNib() {
super.awakeFromNib()
}
func configure(withViewModel viewModel: SensorItemPresentable) -> (Void) {
txtIndex.text = viewModel.id!
txtSensorItem.text = viewModel.textValue!
sensorSwitch.isOn = viewModel.status!
}
}
Here is the code when I do the tableview binding:
override func viewDidLoad() {
super.viewDidLoad()
let nib = UINib(nibName: "SensorCell", bundle: nil)
tableViewItems.register(nib, forCellReuseIdentifier: identifier)
viewModel = SensorViewModel()
self.viewModel?.items.asObservable().bind(to: self.tableViewItems.rx.items(cellIdentifier: identifier, cellType: SensorCell.self)) { index, item, cell in
cell.sensorSwitch.rx.isOn
.subscribe({ status in
//on first time loading the view, if my database has 5 items it will run this 5 times
print("cell switch set to: \(status)")
})
.disposed(by: cell.cellBag)
cell.configure(withViewModel: item)
}.disposed(by: bag)
}