Skip to content

Instantly share code, notes, and snippets.

@xmhafiz
Created October 20, 2022 14:17
Show Gist options
  • Save xmhafiz/315c95897106082d3b864a829a31eb64 to your computer and use it in GitHub Desktop.
Save xmhafiz/315c95897106082d3b864a829a31eb64 to your computer and use it in GitHub Desktop.
func setupPublishers() {
// 1
NotificationCenter.default
.publisher(for: UITextField.textDidChangeNotification, object: emailTextField)
.map { ($0.object as! UITextField).text ?? "" }
.assign(to: \.email, on: viewModel)
.store(in: &cancellables)
NotificationCenter.default
.publisher(for: UITextField.textDidChangeNotification, object: passwordTextField)
.map { ($0.object as! UITextField).text ?? "" }
.assign(to: \.password, on: viewModel)
.store(in: &cancellables)
// 2
viewModel.isSubmitEnabled
.assign(to: \.isEnabled, on: submitButton)
.store(in: &cancellables)
// 3
viewModel.$state
.sink { [weak self] state in
switch state {
case .loading:
self?.submitButton.isEnabled = false
self?.submitButton.setTitle("Loading..", for: .normal)
self?.hideError(true)
case .success:
self?.showResultScreen()
self?.resetButton()
self?.hideError(true)
case .failed:
self?.resetButton()
self?.hideError(false)
case .none:
break
}
}
.store(in: &cancellables)
}
@objc func onSubmit() {
// 4
viewModel.submitLogin()
}
func resetButton() {
// 5
submitButton.setTitle("Login", for: .normal)
submitButton.isEnabled = true
}
func showResultScreen() {
// show another view controller once success
}
// 6
func hideError(_ isHidden: Bool) {
errorLabel.alpha = isHidden ? 0 : 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment