title: Download and write a file with Retrofit and RxJava
body: <p>I'm downloading a pdf file with retrofit, the way that i'm downloading it is by blocks. I use the <code>Content-Range</code> header to obtain a range of bytes, then i need to write these bytes on a <code>file</code> the problem is the order to write them. I'm using the <code>flatMap()</code> function to return an observable for each request that must be done to download the file.</p>
  
  <pre><code>.flatMap(new Func1&lt;Integer, Observable&lt;Response&gt;&gt;() {
                  @Override
                  public Observable&lt;Response&gt; call(Integer offset) {
                      int end;
  
                      if (offset + BLOCK_SIZE &gt; (contentLength - 1))
                          end = (int) contentLength - 1 - offset;
  
                      else
                          end = offset + BLOCK_SIZE;
  
                      String range = getResources().getString(R.string.range_format, offset, end);
  
                     return ApiAdapter.getApiService().downloadPDFBlock(range);
                  }
              })
  </code></pre>
  
  <p>The <code>downloadPDFBlock</code> receive an strings that is needed by a header : <code>Range: bytes=0-3999</code>. Then i use subscribe function to write the bytes downloaded</p>
  
  <pre><code>subscribe(new Subscriber&lt;Response&gt;() {
                  @Override
                  public void onCompleted() {
                      Log.i(LOG_TAG, file.getAbsolutePath());
                  }
  
                  @Override
                  public void onError(Throwable e) {
                      e.printStackTrace();
                  }
  
                  @Override
                  public void onNext(Response response) {
                      writeInCache(response);
                      }
                  }
              });
  </code></pre>
  
  <p>But the problem is that the writing process is made unordered. For example: if the <code>Range: bytes=44959-53151</code> is downloaded first, these will be the bytes that will be written first in the file. I have read about <code>BlockingObserver</code> but i don't know if that could be a solution.</p>
  
  <p>I hope you could help me.</p>