我正在创建一个自定义的 observable,它将呈现一个 UIAlertController,它希望在按下时触发 API 调用。但是,除非我手动订阅它,否则我似乎无法弹出警报。有没有办法从 viewModel 触发这个?
MyController.swift
class MyController: UIViewController {
@IBOutlet weak var nextBarButton: UIBarButtonItem!
var viewModel: ViewModel!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = ViewModel( nextBarButton.rx.tap.asDriver(), alertController()asDriver(onErrorJustReturn: ""))
}
func alertController() -> Observable<String> {
return Observable.create { [weak alert = self] observer in
guard let alert = alert else {
observer.on(.completed)
return Disposables.create()
}
let alertVc = UIAlertController(title: "My Title", message: "My Message", preferredStyle: .alert)
let submit = UIAlertAction(title: "Continue", style: .default) { _ in
observer.onNext("Test")
observer.on(.completed)
}
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
observer.on(.completed)
}
alertVc.addAction(cancel)
alertVc.addAction(submit)
alert.present(alertVc, animated: true, completion: nil)
return Disposables.create {
alertVc.dismiss(animated: true, completion: nil)
}
}
}
}
ViewModel.swift
public final class ViewModel {
init(_ manager: SessionManager, _ trigger: Driver<Void>, _ alert: Driver<String>) {
let _ = trigger.withLatestFrom(alert)
.flatMap { text in
return manager.rx
.request(urlRequest: Api.test)
.retry(3)
.asDriverOnErrorJustComplete()
}
}
}