Search code examples
swiftrx-swiftrx-cocoa

Observe two sources of data at once


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?


Solution

  • 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/