Search code examples
rx-swift

I can't subscribe publishSubject from embed view controller in swift


I have MainViewController that contains ContainerView. and ContainerView have embeded segue that indicate ThirdViewController

In ThirdViewController, I create PublishSubject, If I select something in PickerView then emit the value into PublishSubject. enter image description here

then MainViewController subscribe PublishSubject from ThirdViewController.

so if this success , in MainViewController I will get value from PickerView.

But my problem is I can't get anything, even maybe can't subscribe.

what is problem??? what can I do ???

MainViewController

if  let thirdVC = self.storyboard?.instantiateViewController(withIdentifier:"ThirdViewController") as? ThirdViewController {
                    print("third segue success")

                    thirdVC.selectFeelingSubject.subscribe(onNext : {
                        print($0)

                    }).disposed(by: self.disposeBag)

ThirdViewController

var selectFeelingSubject = PublishSubject<String>()



 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    selectFeelingSubject.onNext(feelingArray[row])

}

Solution

  • The code:

    if  let thirdVC = self.storyboard?.instantiateViewController(withIdentifier:"ThirdViewController") as? ThirdViewController {
        print("third segue success")
        thirdVC.selectFeelingSubject.subscribe(onNext : {
            print($0)
        })
        .disposed(by: self.disposeBag)
    

    Is not giving you the view controller that is in the main view controller. It is instantiating an entirely new view controller.

    You need the actual one that is in the main view controller. Try this instead:

    let thirdVC = self.children[0] as! ThirdViewController
        thirdVC.selectFeelingSubject.subscribe(onNext : {
            print($0)
        })
        .disposed(by: self.disposeBag)
    

    If you have more than one child view controller, you will need to change the 0 to the appropriate number so you are getting the correct child.