Skip to content
Khoa Pham@onmyway133

How to make UIButton tap event observable with RxSwift in iOS

1 min read

I really like the convenient button.rx.tap from RxCocoa, but the swizzling part of it is a big red flag to me.

It’s easy to make our own tap event from UIButton

import UIKit
import RxSwift

final class RxButton: UIButton {
    let tap = PublishSubject<()>()

    override init(frame: CGRect) {
        super.init(frame: frame)

        addTarget(self, action: #selector(buttonTouched), for: .touchUpInside)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }

    @objc private func buttonTouched() {
        tap.onNext(())
    }
}

Then we can use make use of it. Here we use compactMap from RxSwift 5.0 to compact optional stream from Observable<Invoice?>

Observable
.combineLatest(viewModel.invoice.compactMap({ $0 }), buyButton.tap)
.subscribe({ event in
    guard let element = event.element else {
        return

    self.performBuy(invoice: element.0)
})
.disposed(by: bag)

Type to search titles and full text.

↑ ↓ move↵ openPagefind