Two way binding between UISearch bar text and view model property in IOS RxSwift

Viewed 276

I have the following code to set up binding.

viewModel.searchTerm
            .bind(to: searchBar.rx.text)
        .disposed(by: self.disposeBag)

Basically I am looking at setting up two way binding between view model property "searchTerm" and the text property of UISearchBar.

The view model property has been defined as below in the viewModel:

var searchTerm = BehaviorRelay<String>(value: "")

This seems to be a one way binding and I do not see the view model property getting updated when user enters a text in the UISearchBar.

How should I modify this to set up two way binding?

1 Answers

The code you have goes from the view model to the UI element. All you need to do is add code that goes from the element to the view model.

searchBar.rx.text
    .bind(to: viewModel.searchTerm)
    .dispose(by: disposeBag)

This works because a UI element does not emit a value when programmatically changed, only when changed by the user.

That said, I don't recommend two-way bindings. You should maintain a unidirectional data flow as much as possible.

Related