Search code examples
swiftrx-swift

How does RxSwift work if you click a UIButton?


I've just started learning RxSwift. I've added a UIButton with an observable in and a suscribe method that should trigger everytime data changes, but I don't get it to work. What am I missing?

@IBAction func buttonAction(_ sender: Any) {
    publishableSubject.onNext("GURKA")
}

override func viewDidLoad() {
    super.viewDidLoad()

    let bag = DisposeBag()
    _ = publishableSubject.subscribe(onNext: {
        print($0)
    }).disposed(by: bag)
}

Solution

  • Your dispose bag is local so it de-inits when viewDidLoad exits and that will dispose the observable chain you setup. For what you describe, just moving the dispose bag to the class level should fix it.

    let publishableSubject = PublishSubject<String>()
    let bag = DisposeBag()
    
    @IBAction func buttonAction(_ sender: Any) {
        publishableSubject.onNext("GURKA")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        publishableSubject
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: bag)
    }
    

    You might want to consider importing the RxCocoa library as well. It sets up the action for you so you can write less code:

    override func viewDidLoad() {
        super.viewDidLoad()
    
        myButton.rx.tap
            .map { "GURKA" }
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: bag)
    }