按下按钮时可观察到 RxSwift 触发器
Posted
技术标签:
【中文标题】按下按钮时可观察到 RxSwift 触发器【英文标题】:RxSwift trigger observable on button tap 【发布时间】:2017-10-30 02:18:31 【问题描述】:我正在创建一个自定义的 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()
【问题讨论】:
【参考方案1】:您在ViewModel
中忘记了subscribe()
,当链接来自UIButton
的事件时,您应该flatMapLatest
。它应该看起来像:
public final class ViewModel
init(_ manager: SessionManager, _ trigger: Driver<Void>, _ alert: Driver<String>)
let _ = trigger.flatMapLatest alert
.flatMap text in
return manager.rx
.request(urlRequest: Api.test)
.retry(3)
.asDriverOnErrorJustComplete()
.subscribe()
【讨论】:
以上是关于按下按钮时可观察到 RxSwift 触发器的主要内容,如果未能解决你的问题,请参考以下文章
RxSwift - 在 UISearchBar 中以编程方式触发搜索