1

Observing a UITextfield's text value with RxSwift as in code example below does not get updated when programmatically setting the textfield's value like this customTextField.text = "Hello World"

customTextField.rx.text
            .bind(onNext: { textValue in
                print( textValue )
            }).disposed(by: disposeBag)

I have realized that this is due to setting the value programmatically does not fire the valueChanged control property event.

How would I go about ensuring that the valueChanged event gets fired when setting the value programmatically?

Kyle Wood
  • 11
  • 1
  • 2
  • What you are asking for is bad practice. You programmatically update the text field as a result of a change in your model so you shouldn't need to update your model when the text field is programmatically updated. Doing so is breaking every architectural paradigm in existence. Whether you are using MVC, MVVM, VIPER or whatever, this is bad practice. – Daniel T. Jan 28 '20 at 17:58
  • @DanielT. I am aware that it is bad practice but I needed to make use of this hack in a particular use-case. – Kyle Wood Jan 29 '20 at 06:27

1 Answers1

-1

I found a solution (It is a hack) to my question.

Override the UITextField's text property and add a didSet() and then force the sending of the event like this sendActions(for: .valueChanged).

So the following worked for me

private class CustomTextField: UITextField {
    override var text: String? {
        didSet {
           sendActions(for: .valueChanged)
        }
    }
}

...

customTextField.rx.text
            .bind(onNext: { textValue in
                print( textValue )
            }).disposed(by: disposeBag)

...

customTextField.text = "Hello World" 

The following will result in Hello World being printed out as expected, thus the valueChanged property was fired when the customTextField's value was set programmatically.

Does anyone have a better solution? Got inspiration from: https://stackoverflow.com/a/46900006/10263618 and https://github.com/ReactiveX/RxSwift/issues/551

Kyle Wood
  • 11
  • 1
  • 2