Andrej Naumovski
Andrej Naumovski

Reputation: 573

swift - performSegue not working in RxSwift Observable subscribe

I have the following code:

loginViewModel.facebookLogin
.asObservable()
subscribe() { [unowned self] facebookLogin in
     if let isLoggedIn = facebookLogin.element?.isLoggedIn {
         if isLoggedIn {
              elf.performSegue(withIdentifier: "toRestaurantSelect", sender: self)
              }
      }

     if let didLoginFail = facebookLogin.element?.didLoginFail {
         self.errorLabel.isHidden = !didLoginFail
     }
  }
.disposed(by: disposeBag)

The facebookLogin is a Variable and is updated when the user logs in. However, the performSegue is not called (the condition is true). Strangely enough, if I turn on Slow animations in the emulator the segue is executed. When Slow animations are turned off the segue doesn't execute (the Facebook login works). Any help is appreciated. Thanks!

Upvotes: 0

Views: 438

Answers (2)

DavidA
DavidA

Reputation: 3172

Do the observation with the main scheduler:

loginViewModel.facebookLogin
.asObservable()

// Switch to the main scheduler
.observeOn(MainScheduler.instance)


subscribe() { [unowned self] facebookLogin in
     if let isLoggedIn = facebookLogin.element?.isLoggedIn {
         if isLoggedIn {
              elf.performSegue(withIdentifier: "toRestaurantSelect", sender: self)
              }
      }

     if let didLoginFail = facebookLogin.element?.didLoginFail {
         self.errorLabel.isHidden = !didLoginFail
     }
  }
.disposed(by: disposeBag)

Upvotes: 1

3lidev
3lidev

Reputation: 30

i think you should use the main thread to make it work

    loginViewModel.facebookLogin
        .asObservable()
        .subscribe() { [unowned self] facebookLogin in
            if let isLoggedIn = facebookLogin.element?.isLoggedIn {
                if isLoggedIn {


                    DispatchQueue.main.async {
                        self.performSegue(withIdentifier: "toRestaurantSelect", sender: self)

                    }



                }
            }

            if let didLoginFail = facebookLogin.element?.didLoginFail {
                self.errorLabel.isHidden = !didLoginFail
            }
        }
        .disposed(by: disposeBag)

Upvotes: 2

Related Questions