我有一个init,它在我的viewModel上为rxSwift设置观察者的处理
init(login: Observable<String>, password: Observable<String>, buttonPress: Observable<Void>) {
let userInputs = Observable.combineLatest(login, password) { (login, password) -> (String, String) in
return (login, password)
}
let callFromPress = buttonPress
.withLatestFrom(userInputs)
.map { (login, password) in
self.makeLoginRequest(userLogin: login, loginPassword: password, loginSecret: self.loginSecret, deviceToken: self.deviceToken)
}
}
然而,当我点击按钮时,没有任何反应。它连接在VC中,因为:
buttonPress: self.loginView.loginButton.rx.tap.asObservable()
关于按钮敲击为什么没有触发任何错误的任何解决方案?
更新
init(login: Observable<String>, password: Observable<String>, buttonPress: Observable<Void>) {
let userInputs = Observable.combineLatest(login, password) { (login, password) -> (String, String) in
return (login, password)
}
buttonPress.subscribe(onNext: { each in
print(each)
.withLatestFrom(userInputs)
.map { (login, password) in
self.makeLoginRequest(userLogin: login, loginPassword: password, loginSecret: self.loginSecret, deviceToken: self.deviceToken)
}
}).disposed(by: self.disposeBag)
}
错误:
无关的参数标签'onNext:'在通话中
更新2:
init(login: Observable<String>, password: Observable<String>) {
// each time the login and password change, returns login and string value
didTapLoginButton = { [weak self] _ in
// allows for strong self reference
guard let `self` = self else { return }
Observable.combineLatest(login, password) { (login, password) in
//
}
.subscribe(onNext: { response in
self.makeLoginRequest(userLogin: login, loginPassword: password, loginSecret: self.loginSecret, deviceToken: self.deviceToken)
// do something with your response
})
.disposed(by: self.disposeBag)
}
}
答案 0 :(得分:2)
添加.subscribe
。在具有订户之前,可观察者不会发送事件。
示例:
let observable = Observable.from([1,2,3,4,5,6]) // won't send events. It's only the declaration.
当您订阅它时,事情就会发生:
observable.subscribe(onNext: { each in
print(each) // Will print each number
})
.disposed(by: disposeBag) // add a dispose bag
我没有尝试过,但在你的特定情况下,我会做这样的事情:
1-在viewModel
中,添加一个clousure属性:
var didTapLoginButton: () -> Void = { _ in }
2-在viewController
- viewDidLoad()
方法中:
self.loginView.loginButton.rx.tap.asObservable()
.subscribe(onNext: { [weak self] _ in
self?.viewModel.didTapLoginButton()
})
.disposed(by: bag)
3-在viewModel
:
init(login: Observable<String>, password: Observable<String>) {
didTapLoginButton = { [weak self] _ in
// This let you call self as strong reference instead optional
guard let `self` = self else { return }
Observable.combineLatest(login, password) { (login, password) -> (String, String) in
self.makeLoginRequest(userLogin: login, loginPassword: password, loginSecret: self.loginSecret, deviceToken: self.deviceToken)
}
.subscribe(onNext: { response in
// do something with your response
})
.disposed(by: bag)
}
}
答案 1 :(得分:1)
就我而言,我正在做
subscribe(onNext: { [weak self] in
我应该这样做
subscribe(onNext: { [weak self] _ in
这消除了错误