Reputation: 450
Hi I'm learning some RxSwift, I don't understand why makeLoginRequest is called two times...when login is correct i push to an other controller, but the observable still notifies an other event so it push two times the next controller..
In the viewModel the code is this:
let userName : Driver<String>
let password : Driver<String>
var credentials : Driver<(String, String)> {
return Driver.combineLatest(userName, password) { usr, pwd in
return (usr, pwd)
}
}
var credentialValid : Driver<Bool> {
let usrValid = userName
.map { $0.rangeOfString("@") != nil }
let pwdValid = password
.map { $0.utf8.count > 5 }
return Driver.combineLatest(usrValid, pwdValid) { usr, pwd in
return (usr && pwd)
}
}
func login() -> Observable<Login?>
{
return credentials.asObservable()
.observeOn(MainScheduler.instance)
.flatMapLatest { credential -> Observable<Login?> in
return self.makeLoginRequest(user: credential.0, password: credential.1)
}
}
func makeLoginRequest(user user: String, password: String) -> Observable<Login?>
{
return self.provider
.request(APIProvider.Login(credentials: (user, password)))
.debug()
.mapObjectOptional(Login.self)
}
and in the controller
loginModel = LoginViewModel(provider: apiProvider! as! RxMoyaProvider<APIProvider>, userName: userTextField.rx_text.asDriver(), password: passwordTextField.rx_text.asDriver())
loginModel.credentialValid
.driveNext { [unowned self] valid in
self.loginButton.enabled = valid
}
.addDisposableTo(disposeBag)
loginButton.rx_tap
.debug()
.flatMap({ self.loginModel.login() })
.subscribeNext({ login in
// handle here login data
})
.addDisposableTo(disposeBag)
Anyone can explain what's going on?
Thanks!
Upvotes: 0
Views: 2237
Reputation: 7739
Your problem probably lies with code you haven't shown: userName
, password
, or provider
. Also, you included credentialsValid
, but it's not used. So again, maybe something with that method and how you're using it in your actual code.
On a side note, you shouldn't be using subscribeNext
nested like that in your view controller. You should be using flatMap
and subscribing to just the final Observable
.
See if you can come up with a code example that shows your problem that we can actually run, and then we can help. You'll probably figure out what's wrong on your own by making that example.
Upvotes: 1