title: RxJava: observable that contains an asynchronous call
body: <p>I'm trying to understand RxJava and running into the following situation.</p>
  
  <p>Consider the following method that returns an observable which calls <code>NsdManager.registerService</code>. The registerService method needs a listener which is called when registration succeeded (or failed).</p>
  
  <pre><code>public Observable&lt;Boolean&gt; registerService() {
      return Observable.create(new Observable.OnSubscribe&lt;Boolean&gt;() {
  
          @Override
          public void call(Subscriber&lt;? super Boolean&gt; subscriber) {
              nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener);
  
              // how to proceed?
          }
      });
  }
  </code></pre>
  
  <p>The observer can provide a notification only after the listener has been called, but the listener is called asynchronously.</p>
  
  <p>How can I do this with RxJava?</p>
  
  <hr>
  
  <p>I came up with the following, using a BehaviorSubject. Don't know if it is the best solution, but it works.</p>
  
  <pre><code>private BehaviorSubject&lt;Boolean&gt; registrationSubject;
  
  public Observable&lt;Boolean&gt; registerService() {
      registrationSubject = BehaviorSubject.create();
  
      Observable.create(new Observable.OnSubscribe&lt;Boolean&gt;() {
          @Override
          public void call(Subscriber&lt;? super Boolean&gt; subscriber) {
              NsdServiceInfo serviceInfo  = new NsdServiceInfo();
              serviceInfo.setServiceName(serviceName);
              serviceInfo.setServiceType(NSD_SERVICE_TYPE);
              serviceInfo.setPort(serverSocket.getLocalPort());
  
              nsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registrationListener);
          }
      }).subscribe(registrationSubject);
  
      return registrationSubject;
  }
  
  private NsdManager.RegistrationListener registrationListener = new NsdManager.RegistrationListener() {
      @Override
      public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
          registrationSubject.onNext(false);
          registrationSubject.onCompleted();
      }
  
      @Override
      public void onServiceRegistered(NsdServiceInfo serviceInfo) {
          registrationSubject.onNext(true);
          registrationSubject.onCompleted();
      }
  
      @Override
      public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) { }
  
      @Override
      public void onServiceUnregistered(NsdServiceInfo serviceInfo) {}
  };
  </code></pre>