I have a LoginViewModel and LoginViewController class. In LoginViewController there is 2 textfield userName, password, and a Login Button, when user click Login button username and password field is validated in LoginViewModel class, if it is empty then a respective message is passed to LoginViewController class and message in displayed in respective textfield.
class LoginViewModel : LoginViewModelProtocol {
var errorObservable: PublishSubject<String> = PublishSubject<String>()
var userName: BehaviorRelay<String> = BehaviorRelay(value: "")
var password: BehaviorRelay<String> = BehaviorRelay(value: "")
let disposeBag = DisposeBag()
var apiClient : ApiClientProtocol
public init(fetcher : ApiClientProtocol) {
apiClient = fetcher
}
func validateUserName(_ value: String) -> Bool {
if value.count == 0 {
errorObservable.onNext("This field is required")
return false
}
return true
}
func validatePassword(_ value: String) -> Bool {
if value.count == 0 {
errorObservable.onNext("This field is required")
return false
}
return true
}
func onLoginButtonClick(){
if self.validateUserName(userName.value) && self.validatePassword(password.value) {
// apiClient.performLogin(userName: userName.value, password: password.value)
}
}
}
//validateUserName and validatePassword should notify username and password field respectively.
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
let disposeBag = DisposeBag()
var viewModel: LoginViewModelProtocol!
override func viewDidLoad() {
super.viewDidLoad()
initialiseUI()
configureBinding()
}
func configureBinding() {
usernameTextField.rx.text
.orEmpty
.bind(to: viewModel.userName)
.disposed(by: disposeBag)
passwordTextField.rx.text
.orEmpty
.bind(to: viewModel.password)
.disposed(by: disposeBag)
viewModel.errorObservable.asObserver().subscribe(onNext: { (error) in
self.updateUI(error)
}, onDisposed: {})
}
func updateUI(_ error : String){
let fontS = UIFont.systemFont(ofSize: 12)
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.red,
NSAttributedString.Key.font : fontS
] as [NSAttributedString.Key : Any]
self.passwordTextField.attributedPlaceholder = NSAttributedString(string: error, attributes: attributes)
}
}
I want to show error message in both textfield when both are empty How will I pass value with errorObserver for both textField and password when they are empty with RxSwift?