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)
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With