I'm still a beginner in using Combine. I practice it on and off. Anyway, I have a view model to see changes in two text fields in my view controller as follows.
// ViewModel //
import Foundation
import Combine
class LoginViewModel {
var cancellable = [AnyCancellable]()
init(username: String, password: String) {
myUsername = username
myPassword = password
}
@Published var myUsername: String?
@Published var myPassword: String?
func validateUser() {
print("\(myUsername)")
print("\(myPassword)")
}
}
And my view controller goes as follows.
// ViewController //
import UIKit
import Combine
class HomeViewController: UIViewController {
// MARK: - Variables
var cancellable: AnyCancellable?
// MARK: - IBOutlet
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
cancellable = NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification, object: usernameTextField)
.sink(receiveValue: { result in
if let textField = result.object as? UITextField {
if let text = textField.text {
let loginViewModel = LoginViewModel(username: text, password: "")
loginViewModel.validateUser()
}
}
})
}
}
So I use NSNotification as a publisher to see text changes over one of the text fields. And I cannot see text changes over two of them at the same time. Is there a better approach in seeing text changes over two text fields at the same time using Combine?
Muchos thankos.