我对RxSwift还比较陌生,并且在开发过程中尝试实现最佳实践。
在我的主视图控制器上,我必须显示一个自定义警报视图控制器,用户在其中输入文本到文本字段并点击确认。假设文本是有效的,警报将被解除,并推送一个新的视图控制器。
为了避免使用回调或委托,我呈现警报视图控制器,然后我的主视图控制器订阅警报视图控制器的textfield并确认按钮。
订阅不同的视图控制器是不好的做法吗?
伪码:
let alert = viewModel.textFieldAlert()
present(alert)
alertSubscriptions(alert)alertSubscriptions
alert.textField.rx.text.subscribe(onNext: { [weak self] text in
self?.viewModel.numberOfItems.value = text ?? ""
}).addDisposableTo(disposeBag)
alert.confirmButton.rx.tap.subscribe(onNext: { [weak self] _ in
guard self != nil else { return }
if !self!.viewModel.validText { return }
alert.dismiss()
self!.alertConfirmed()
}).addDisposableTo(disposeBag)我已经测试过这段代码,它的工作没有任何问题。
发布于 2017-05-04 23:57:26
我碰巧写了一篇关于这个主题的文章:https://medium.com/@danielt1263/encapsulating-the-user-in-a-function-ec5e5c02045f --本文使用的是承诺--但是在使用Rx时,同样的过程和IMHO应该完成。
我认为这样的事情会更好:
extension UIViewController {
func infoAlert(title: String, message: String, isValidInput: @escaping (String) -> Bool) -> Observable<String> {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let confirm = PublishSubject<Void>()
let confirmed = UIAlertAction(title: "OK", style: .default) { (action) in
confirm.onNext()
}
let text = PublishSubject<String>()
alert.addTextField { textField in
textField.placeholder = "Enter Data"
_ = textField.rx.text.orEmpty.bind(to: text)
}
_ = text.map(isValidInput)
.bind(to: confirmed.rx.isEnabled)
alert.addAction(confirmed)
present(alert, animated: true, completion: nil)
return confirm.withLatestFrom(text)
}
}通过将所有代码包含在序列发射器函数(即返回可观测值的函数)中,您就打开了将该函数添加到可观测对象链中的大门。
例如,上面的函数可以是在视图控制器中按下按钮的flatMapped,或者添加到更复杂的可观察管道中。
https://stackoverflow.com/questions/43790332
复制相似问题