按钮点击时可以观察到RxSwift触发器

时间:2017-10-30 02:18:32

标签: rx-swift rx-cocoa

我正在创建一个自定义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 个答案:

答案 0 :(得分:0)

您忘记subscribe() ViewModelflatMapLatestUIButton来自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() } } 。它应该看起来像:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) { /* do what you want */ }