bindrx-swiftpublishsubject

RxSwift: binding PublishSubject to multiple buttons and receive sender


I am working on an app that presents 26 (alphabet) buttons. Right now they're all connected to the same function in the ViewController, that in turn calls another function in the ViewModel, and finally this function calls publishSubject.onNext(). The ViewController subscribes to the PublishSubject and that's the whole circle.

The reason I did it this way, instead of binding the publish subject to the buttons' tap, is that I have to know who the sender is. Is there anyway to do so? If there isn't, is there a more intelligent design than mine in head?

Thanks!


Solution

  • You can make the PublishSubject to send String and then each time a button is tapped, you can send the title of the button as the event data.

    publishSubject.onNext(sender.title)

    That way you can distinguish the sender from the ViewModel and keep your current design.

    UPDATE:

    After reading your question again I realized you are trying to achieve a more reactive way than what you currently have. So instead of pulling an IBActions from all the buttons, you can just have IBOutlets and on viewDidLoad bind all those buttons to the PublishSubject. Something like this:

    aButton
       .rx
       .tap.map { _ in 
          aButton.title
       }
       .bindTo(viewModel.buttonTapped)
       .disposed(by:disposeBag)