title: When do you use map vs flatMap in RxJava?
body: <p>When do you use <code>map</code> vs <code>flatMap</code> in <strong>RxJava</strong>?</p>
  
  <p>Say, for example, we want to map Files containing JSON into Strings that contain the JSON--</p>
  
  <p>Using <code>map</code>, we have to deal with the <code>Exception</code> somehow. But how?:</p>
  
  <pre><code>Observable.from(jsonFile).map(new Func1&lt;File, String&gt;() {
      @Override public String call(File file) {
          try {
              return new Gson().toJson(new FileReader(file), Object.class);
          } catch (FileNotFoundException e) {
              // So Exception. What to do ?
          }
          return null; // Not good :(
      }
  });
  </code></pre>
  
  <p>Using <code>flatMap</code>, it's much more verbose, but we can forward the problem down the chain of <code>Observables</code> and handle the error if we choose somewhere else and even retry:</p>
  
  <pre><code>Observable.from(jsonFile).flatMap(new Func1&lt;File, Observable&lt;String&gt;&gt;() {
      @Override public Observable&lt;String&gt; call(final File file) {
          return Observable.create(new Observable.OnSubscribe&lt;String&gt;() {
              @Override public void call(Subscriber&lt;? super String&gt; subscriber) {
                  try {
                      String json = new Gson().toJson(new FileReader(file), Object.class);
  
                      subscriber.onNext(json);
                      subscriber.onCompleted();
                  } catch (FileNotFoundException e) {
                      subscriber.onError(e);
                  }
              }
          });
      }
  });
  </code></pre>
  
  <p>I like the simplicity of the <code>map</code>, but the error handling of <code>flatmap</code> (not the verbosity). I haven't seen any best practices on this floating around and I'm curious how this is being used in practice.</p>