Download progress with RxJava, OkHttp and Okio in Android

Rafael picture Rafael · Apr 30, 2015 · Viewed 13.3k times · Source

In our app I download an image file with this code. I need to show download progress(downloaded bytes in percentage) on UI. How I can get download progress in this code? I searched for solution, but still can't manage to do it on my own.

Observable<String> downloadObservable = Observable.create(
                    sub -> {
                        Request request = new Request.Builder()
                                .url(media.getMediaUrl())
                                .build();
                        Response response = null;
                        try {
                            response = http_client.newCall(request).execute();
                            if (response.isSuccessful()) {
                                Log.d(TAG, "response.isSuccessful()");
                                String mimeType = MimeTypeMap.getFileExtensionFromUrl(media.getMediaUrl());
                                File file = new File(helper.getTmpFolder() + "/" + helper.generateUniqueName() + "test." + mimeType);
                                BufferedSink sink = Okio.buffer(Okio.sink(file));
                                sink.writeAll(response.body().source());
                                sink.close();
                                sub.onNext(response.toString());
                                sub.onCompleted();
                            } else {
                                sub.onError(new IOException());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
            );

            Subscriber<String> mySubscriber = new Subscriber<String>() {
                @Override
                public void onNext(String responseString) {
                    Log.d(TAG, "works: " + responseString);
                }
            };
            downloadObservable
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(mySubscriber);

Answer

inmyth picture inmyth · Apr 30, 2015

This is what I would do to display progress.

Observable<String> downloadObservable = Observable.create(
  sub -> {
          InputStream input = null;
          OutputStream output = null;
          try {
          Response response = http_client.newCall(request).execute();
           if (response.isSuccessful()) {                 
             input = response.body().byteStream();
             long tlength= response.body().contentLength();

             output = new FileOutputStream("/pathtofile");
             byte data[] = new byte[1024];

             sub.onNext("0%");
             long total = 0;
             int count;
             while ((count = input.read(data)) != -1) {
               total += count;

               sub.onNext(String.valueOf(total*100/tlength) + "%");

               output.write(data, 0, count);
             }
             output.flush();
             output.close();
             input.close();
           }
          } catch(IOException e){
            sub.onError(e);
          } finally {
                if (input != null){
                    try {
                        input.close();
                    }catch(IOException ioe){}
                }
                if (out != null){
                    try{
                        output.close();
                    }catch (IOException e){}                        
                }
          }
        sub.onCompleted();
   }
);

And use the Subscriber that has the complete abstract methods.

Subscriber<String> mySubscriber = new Subscriber<String>() {

@Override
public void onCompleted() {
  // hide progress bar
}

@Override
public void onError(Throwable e) {
  // hide progress bar
}

@Override
public void onNext(String percentProgress) {
  // show percentage progress
}
};