title: How to avoid piling up callbacks or "callback hell"?
body: <p>My program makes heavy use of (possibly) asynchronous calls where the return value is not immediately available, thus there are a lot of methods like this:</p>
  
  <pre><code>// A simple callback interface
  public interface GetFooCallback
  {
      void onResult(Foo foo);
  };
  
  // A method that magically retrieves a foo
  public void getFoo(long fooID, GetFooCallback callback)
  {
      // Retrieve "somehow": local cache, from server etc.
      // Not necessarily this simple.
      Foo foo = ...; 
  
      callback.onResult(foo);
  }
  </code></pre>
  
  <p>However, as there are lots of things that are dependent of the last call like this, they start to pile up:</p>
  
  <pre><code>// Get foo number 42
  fooHandler.getFoo(42, new GetFooCallback()
  {
      @Override
      public void onResult(final Foo foo)
      {
          // Foo 42 retrieved, get a related Bar object
          barHandler.getBar(foo.getBarID(), new GetBarCallback()
          {
              @Override
              public void onResult(final Bar bar)
              {
                  // Send a new Zorb(foo, bar) to server
                  zorbHandler.sendZorbToServer(new Zorb(foo, bar), new ZorbResponseHandler()
                  {
                      @Override
                      public void onSuccess()
                      {
                          // Keep dancing
                      }
  
                      @Override
                      public void onFailure()
                      {
                          // Drop the spoon
                      }
                  });
              }
          });
      }
  });
  </code></pre>
  
  <p>This "works", but it starts to feel rather icky when the pile keeps growing and it's difficult to keep track of what's happening. So, the question is: How do I avoid this pile-up? As I've googled "callback hell", many places suggest RxJava or RxAndroid, but I haven't really found any examples showing how one would convert something like the aforementioned example into a more concise whole.</p>