Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download progress with RxJava, OkHttp and Okio in Android

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);
like image 250
Rafael Avatar asked Apr 30 '15 04:04

Rafael


1 Answers

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
}
};
like image 71
inmyth Avatar answered Sep 29 '22 10:09

inmyth