嗨,我正在学习一些 RxSwift,我不明白为什么 makeLoginRequest 被调用两次......当登录正确时,我推送到另一个控制器,但 observable 仍然通知另一个事件,因此它推送两次下一个控制器。 .
在 viewModel 中,代码是这样的:
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)
}
并在控制器中
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)
任何人都可以解释发生了什么?
谢谢!