title: How to obtain a UIAlertController observable (ReactiveCocoa or RxSwift)?
body: <p>I implemented a "reactive" <code>UIAlertController</code> so I can get an <code>Observable&lt;Int&gt;</code> of the button press. (See code below).</p>
  
  <p>My question, or questions, are:</p>
  
  <ul>
  <li>Is this implementation correct? I don't like storing the observers; I wonder if there's a better solution.</li>
  <li>Or... is there already an implementation of this in ReactiveCocoa or RxSwift?</li>
  </ul>
  
  <p>Here is the implementation. I removed the parts not relevant to te question.</p>
  
  <pre><code>class AlertBuilder {
  
      typealias AlertAction = (Int) -&gt; ()
  
      private let alert: UIAlertController
  
      /** If observable() is called, we keep here the observers to notify them */
      private var observers: [AnyObserver&lt;Int&gt;] = []
  
      init(alert: UIAlertController) {
          self.alert = alert
      }
  
      /** When using observable(), the action is not needed. */
      func button(_ title: String, style: UIAlertActionStyle = .default, action: AlertAction? = nil) -&gt; AlertBuilder {
  
          let buttonIndex = alert.actions.count
          alert.addAction( UIAlertAction(title: title, style: style, handler: { [weak self] _ in
  
              // Callback via action
              action?(buttonIndex)
  
              // Callback via observers
              if let this = self {
                  for observer in this.observers {
                      observer.onNext(buttonIndex)
                      observer.onCompleted()
                  }
                  this.observers = []
              }
          }) )
          return self
      }
  
      /**
       * Returns an Observable that will emit the pressed button index and complete.
       * It's important to keep a reference to the AlertBuilder, otherwise the events won't be received.
       */
      func observable() -&gt; Observable&lt;Int&gt; {
  
          return Observable&lt;Int&gt;.create { observer in
              self.observers.append(observer)
              return Disposables.create()
          }
      }
  }
  </code></pre>
  
  <p>You would use it from a controller, like this:</p>
  
  <pre><code>let alert = UIAlertController(title: "title", message: "msg", preferredStyle: .actionSheet)
  
  let builder = AlertBuilder(alert: alert)
      .button("no", style: .destructive)
      .button("yes")
  
  self.present(alert, animated: true, completion: nil)
  
  self.builder.observable()
      .subscribe(onNext: { buttonIndex in /* ... */ })
      .disposed(by: bag)
  
  // keep reference to builder so observable() works
  self.builder = builder
  </code></pre>