RxSwift Beginners Episode 7 - Login form validations. combineLatest and withLatestFrom operators
combineLastest
사용combineLastest
구현 private func setObservers() {
let observer1 = userNameTextField.rx.text.orEmpty
let observer2 = passwordTextField.rx.text.orEmpty
let observerCombined = Observable.combineLatest(observer1, observer2)
loginButton.rx.tap
.withLatestFrom(observerCombined)
.subscribe(onNext: { (userName, password) in
self.login(userName, password)
})
.disposed(by: disposeBag)
}
Observable.combineLatest
메소드를 통해 한 개의 옵저버로 구현loginButton
)이 탭했을 경우 RxSwift 메소드를 통해 위의 결합한 옵저버 값을 관찰하고, 결과값을 구독해 로그인 여부를 판단하는 login()
메소드 실행import Foundation
import UIKit
import RxSwift
import RxCocoa
class LoginViewController: UIViewController {
@IBOutlet weak var userNameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
title = "Login"
setObservers()
}
private func setObservers() {
let observer1 = userNameTextField.rx.text.orEmpty
let observer2 = passwordTextField.rx.text.orEmpty
let observerCombined = Observable.combineLatest(observer1, observer2)
loginButton.rx.tap
.withLatestFrom(observerCombined)
.subscribe(onNext: { (userName, password) in
self.login(userName, password)
})
.disposed(by: disposeBag)
}
private func login(_ userName: String, _ password: String) {
if isLoginPossible(userName, password) {
guard let foodTableVC = storyboard?.instantiateViewController(withIdentifier: "FoodListViewController") as? ViewController else {
invalidMessage()
return
}
navigationController?.pushViewController(foodTableVC, animated: true)
} else {
invalidMessage()
}
}
private func invalidMessage() {
let alert = UIAlertController(title: "Warning!", message: "Invalid ID or PW!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(alert, animated: true, completion: nil)
}
private func isLoginPossible(_ userName: String, _ password: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format: "SELF MATCHES[c] %@", emailRegEx)
let emailValid: Bool = emailTest.evaluate(with: userName)
let passValid: Bool = (password != "" && password.count >= 6)
return emailValid && passValid
}
}
loginButton
이라는 UIButton에 탭을 통해 함수를 추가하거나, IBOutlet
함수로 login
을 등록해야 한다.RxSwift를 통해 특정 UI 버튼의 탭과 같은 UI 행동 역시 컨트롤할 수 있다는 것에 놀랐다.