0

I'm learning RxSwift and RxCocoa. I've run into this problem:

I have UITextField and UIPickerView and UIButton. UIButton should become enabled once UITextField is valid. There is different validation regex for each item selected from UIPickerView.

This is my code so far:

        textField.rx.text
            .map({ (text) -> Bool in
                return self.validate(text!, self.regex)})
            .subscribe(onNext: { (valid) in
                self.button.alpha = valid ? 1 : 0.5
                self.button.isEnabled = valid
            })
            .disposed(by: disposeBag)

        pickerView.rx.itemSelected.subscribe(onNext: { row, value in
            self.regex = getRegex(row)
        }).disposed(by: disposeBag)

So I'm picking regex first from pickerView then I'm observing text change. The problem appears when I want to input text first and then pick some different regex from pickerView - the button doesn't update, cause no changes to text were made!

So I'm guessing I should somehow zip or merge these two sources (observables?), so that button can observe any change from each of them at once.

How should I approach this problem?

user3554626
  • 425
  • 1
  • 5
  • 9

2 Answers2

1

Have you searched for combineLatest function?

i think it will solve your problem

You can understand it with this blog: http://adamborek.com/combinelatest-withlatestfrom-zip/

Abdo
  • 342
  • 1
  • 8
1

Ok, I kind of solved it (using combineLatest as mentioned by Abdorahman). I posting it for anyone else who'd be looking for something similar:

        let pickObs = pickerView.rx.itemSelected.map { (row, component) -> String? in
            return getRegex(row)
        }

        Observable.combineLatest(textField.rx.text, pickObs.startWith("‍♂️")){ text, regex -> Bool in
            return self.validate(text, regex)
            }.subscribe(onNext: { (valid) in
                self.addNewDevice.alpha = valid ? 1 : 0.5
                self.addNewDevice.isEnabled = valid
            }).disposed(by: disposeBag)

The pickObs.startWith("‍♂️") is there, because I couldn't find the way to pre-select pickerView. (pickerView.selectRow wasn't triggering pickerView.rx.itemSelected code block.

user3554626
  • 425
  • 1
  • 5
  • 9