Search code examples
swiftuikitrx-swift

should I manually dispose a UIButton instance in RxSwift?


I'm new to RxSwift and got confused when reading blogs about it.

Is this a proper way to create a button in a customized view?

    let disposeBag = DisposeBag()
    lazy var followButton: UIButton = {
        let btn = UIButton(frame: .zero)
        btn.rx.tap.subscribe(onNext: { [weak self] in
            // do something when the button is tapped
        }).disposed(by: disposeBag) // this line
        
        return btn
    }()

Is it necessary to use disposed(by: DisposeBag) as long as the button is subscribed(observed)?

Update

 lazy var followButton: UIButton = {
        let btn = UIButton(frame: .zero)
        btn.rx.tap.subscribe(onNext: { [weak self] in
            // do something when the button is tapped
        }) 
        // a warning says 
        // Result of call to 'subscribe(onNext:onError:onCompleted:onDisposed:)' is unused
        
        return btn
    }()

The warning seems to imply the api is designed to connect with another method like disposed. What method should be used here if we don't need disposed?
Or just _ = btn.rx.tap.subscribe...?


Solution

  • UIButton's tap will complete when the button is deinited and therefore doesn't need to be explicitly disposed (unless you want to cancel it before the button deinits.) There's certainly nothing wrong with adding the subscription to a dispose bag, but it's not necessary.

    _ = btn.rx.tap
        .subscribe(onNext: { 
            // do something when the button is tapped.
        })
    

    The above is how you handle it if you don't want the disposeBag.