Search code examples
iosrx-swift

drive can be only called from MainThread


after presenting new UIViewController by code, every where(in viewModel or viewController) using .Drive, I get this error: drive* family of methods can be only called from MainThread

this is how I present new ViewController:

func goToVerifyPage() {

    let verifyVC = VerifyViewController()
    verifyVC.modalTransitionStyle = .flipHorizontal
    self.present(verifyVC, animated: true, completion: nil)
}

and inside VerifyViewController:

override func viewDidLoad() {
        super.viewDidLoad()

        confirmVerifyCodeBTN.rx.tap
            .asDriver()
            .debounce(1)
            .filter({
                self.viewModel.signupEnabled
            })
            .drive(onNext:{  [weak self] _ in
                guard let verifyCode = self?.verificationCodeTF.text  else { return }
                self?.verifyActivateCode(verifyCode)
            }).disposed(by: disposeBag)
}

the error showed after execute .filter line.

in the previos viewController(named loginViewController) I use the same codes but did not getting any error, the only thing that's different between verifyViewController and loginViewController is, using storyboard to presenting that ViewController(loginViewController).

update: when I using this codes for presenting verifyViewController every things going fine:

func goToVerifyPage() {
        DispatchQueue.main.async {
            let verifyVC = VerifyViewController()
            verifyVC.modalTransitionStyle = .flipHorizontal
            self.present(verifyVC, animated: true, completion: nil)
        }
}

Solution

  • My guess is that you were calling goToVerifyPage() from the result of a network request from URLSession. URLSession emits its values on a background thread so when you are ready to switch to the main thread, you should have an .observeOn(MainThread.instance).