0

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)

}
Bruno
  • 1,032
  • 1
  • 16
  • 40

1 Answers1

4
cell.sensorSwitch.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: cell.cellBag)
prex
  • 719
  • 4
  • 17
  • hi @prekshya do you have an idea why we can't use [weak self] when configuring inside let dataSource = RxTableViewSectionedReloadDataSource( configureCell:... – Soufiane.ess Nov 16 '18 at 15:02
  • @Soufiane.ess I don't understand why you can't use [weak self] since I have used it in my projects. Here is a snippet how I used - `dataSource = RxTableViewSectionedReloadDataSource(configureCell: { [weak self] ..` `let cell = tableView.dequeueReusableCell..` `cell.viewModel = self?.viewModel.createCellVM(model: sectionModel)` `return cell` `})` – prex Nov 16 '18 at 16:33