title: Don't re-execute Retrofit call if it's still in progress using RxJava 2
body: <p>My goal is a method that will execute a network call unless the network call is already in progress in which case the caller subscribes to the results of the existing call.</p>
  
  <p>Here is what I have, it mostly works:</p>
  
  <pre><code>private AsyncSubject&lt;Stuff&gt; asyncSubject;
  
  public Observable&lt;Stuff&gt; getStuff() {
      if (asyncSubject == null) {
          asyncSubject = AsyncSubject.create();
          asyncSubject
              .doAfterTerminate(new Action() {
                  @Override
                  public void run() throws Exception {
                      asyncSubject = null;
                  }
              })
              .subscribe();
          retrofitApi.getStuff()
              .subscribe(asyncSubject);
      }
      return asyncSubject
          .someOperatorsHere();
  }
  </code></pre>
  
  <p>This mostly works because asyncSubject nulls itself out on terminate so that any subsequent calls will re-execute the network request.</p>
  
  <p>But there is a bug, there's a window between <code>if (asyncSubject == null)</code> and <code>return asyncSubject</code> where doAfterTerminate can execute and I get a null pointer.</p>
  
  <p>Any ideas how to fix the bug. Maybe there is a more elegant Rx way to do this? Or <code>synchronized</code> block. Or a way to query Retrofit for network progress.</p>