Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get which button is clicked in RxSwift

I have created a common action for an array of my button. I just want to get the which button is tapped.

I have array of buttons like let buttons = [UIButton(), UIButton(), UIButton(),UIButton()].

let observable = Observable.of(buttons[0].rx.tap, buttons[1].rx.tap, buttons[2].rx.tap, buttons[3].rx.tap).merge()
    observable.subscribe(onNext: {
      print("I want to find which button is tapped.")
    }).disposed(by: disposeBag)
like image 808
Ravi Dhorajiya Avatar asked Oct 11 '18 09:10

Ravi Dhorajiya


2 Answers

Just map the tap events to some custom IDs -

let observable = Observable.merge(
  buttons[0].rx.tap.map { 0 },
  buttons[1].rx.tap.map { 1 },
  // etc.
)

observable.subscribe(onNext: { id in
  print("\(id) button is tapped.")
}).disposed(by: disposeBag)
like image 54
Maxim Volgin Avatar answered Nov 13 '22 10:11

Maxim Volgin


The correct answer is to not merge the buttons in the first place. If you want to do four different things, then have four different observables. If they are all doing the same thing, just with different data then simply:

let taps = buttons.enumerated().map { ($0.0, $0.1.rx.tap) }
let toInts = taps.map { index, obs in obs.map { index } }
let mergedTaps = Observable.merge(toInts)

On review, I really like an answer by @Sooraj_snr that has been deleted. Use the buttons' tags instead of their position in the array. It's much more robust.

let tags = buttons
    .map { ($0.rx.tap, $0.tag) }
    .map { obs, tag in obs.map { tag } }
let values = Observable.merge(tags)
like image 25
Daniel T. Avatar answered Nov 13 '22 11:11

Daniel T.