Create signup page with username,password,email and confirm password using rxswift
Solution:
Using signUpViewModel
import RxSwift
import RxCocoa
class SignupViewModel {
let username = BehaviorRelay<String>(value: "")
let password = BehaviorRelay<String>(value: "")
let email = BehaviorRelay<String>(value: "")
let confirmPassword = BehaviorRelay<String>(value: "")
let usernameValid: Observable<Bool>
let passwordValid: Observable<Bool>
let emailValid: Observable<Bool>
let confirmPasswordValid: Observable<Bool>
let signupEnabled: Observable<Bool>
init() {
usernameValid = username.asObservable().map { $0.count >= 10 }
passwordValid = password.asObservable().map { $0.count >= 8 }
emailValid = email.asObservable().map { $0.contains("@") && $0.contains(".") }
confirmPasswordValid = Observable.combineLatest(password.asObservable(), confirmPassword.asObservable()) {
password, confirmPassword in
return password == confirmPassword
}
signupEnabled = Observable.combineLatest(usernameValid, passwordValid, emailValid, confirmPasswordValid) {
$0 && $1 && $2 && $3
}
}
}
Using signupViewController
import UIKit
import RxSwift
import RxCocoa
class SignupViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
@IBOutlet weak var signupButton: UIButton!
let viewModel = SignupViewModel()
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
usernameTextField.rx.text.orEmpty
.bind(to: viewModel.username)
.disposed(by: disposeBag)
passwordTextField.rx.text.orEmpty
.bind(to: viewModel.password)
.disposed(by: disposeBag)
emailTextField.rx.text.orEmpty
.bind(to: viewModel.email)
.disposed(by: disposeBag)
confirmPasswordTextField.rx.text.orEmpty
.bind(to: viewModel.confirmPassword)
.disposed(by: disposeBag)
viewModel.signupEnabled
.bind(to: signupButton.rx.isEnabled)
.disposed(by: disposeBag)
signupButton.rx.tap
.subscribe(onNext: { [weak self] in
guard let self = self else { return }
print("Signup username: \(self.viewModel.username.value)")
})
.disposed(by: disposeBag)
}
}
Comments
Post a Comment