Search code examples
swiftrx-swiftrx-cocoa

combining tap event of 3 buttons with rxSwift


I have 3 buttons

@IBOutlet weak var editGeomButton: UIButton! // 1
@IBOutlet weak var editDataButton: UIButton! // 2
@IBOutlet weak var deleteDataButton: UIButton! // 3

On click of any of this buttons I want below method to be called. With the proper numbers.

func didTap() -> Observable<Int> {

}

didTap().subscribe(onNext: { (tag) in
    switch tag {
    case 1:
        print("Did tap Edit Geom")
    case 2:
        print("Did tap Edit Data")
    case 3:
        print("Did tap Delete geom")
    default:
        print("Invalid tap")
    }
}).disposed(by: disposeBag)

Please help with the code to write in didTap method using Observable? I think this can be achieved using combine operator. But I don't understand how to code this.


Solution

  • I would use an enum instead to avoid the default case:

    enum Actions {
      case editGeom
      case editData
      case deleteGeom
    }
    
    Observable.merge(
      editGeomButton.rx.tap.map { _ in Actions.editGeom },
      editDataButton.rx.tap.map { _ in Actions.editData },
      deleteDataButton.rx.tap.map { _ in Actions.deleteGeom }
    ).subscribe(onNext: {
      switch $0 {
      case .editGeom:
        print("Did tap Edit Geom")
      case .editData:
        print("Did tap Edit Data")
      case .deleteGeom:
        print("Did tap Delete geom")
      }
    }).disposed(by: disposeBag)
    

    Basically, it's just mapping each tap to a value before merging them together.