0
votes

Scenario :

  • Create request

    **Interface**
    
      @GET("someurl.mp4")
      @Streaming
      Call<ResponseBody> downloadFile(); // retrofit2.Call
    
    
    **call**
    
    RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
     //okhttp3.ResponseBody
    Call<ResponseBody> request = retrofitInterface.downloadFile();
    try {
        downloadFile(request.execute().body());
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  • Download bytes by bytes

    private void downloadFile(ResponseBody body) throws IOException {
    
    int count;
    byte[] data;
    data = new byte[1024 * 4];
    long fileSize = body.contentLength();
    Log.i("Download", "downloadFile: " + fileSize);
    InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
    File outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), System.currentTimeMillis() + ".mp4");
    try (OutputStream output = new FileOutputStream(outputFile)) {
        long total = 0;
        long startTime = System.currentTimeMillis();
        Log.i("Download", "downloadFile size: " + fileSize);
        int timeCount = 1;
        while ((count = bis.read(data)) != -1) {
    
            total += count;
            totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
            double current = Math.round(total / (Math.pow(1024, 2)));
    
            int progress = (int) ((total * 100) / fileSize);
    
            long currentTime = System.currentTimeMillis() - startTime;
    
            Download download = new Download();
            download.setTotalFileSize(totalFileSize);
    
            if (currentTime > 1000 * timeCount) {
    
                download.setCurrentFileSize((int) current);
                download.setProgress(progress);
                sendNotification(download);
                timeCount++;
            }
            if (download.getProgress() != 0)
                Log.i("Download", "progress: " + download.getProgress());
    
            output.write(data, 0, count);
        }
        onDownloadComplete();
        output.flush();
        //output.close();
    }
    bis.close();
    }
    

Problem

I am not able to port above code in RxJava using Observable/Single interface. All i want is to download file bytes by bytes for some purpose.

I tried to call downloadFile(request.execute().body()); inside ongoing async operation(RxJava) but didn't work as expected.

1

1 Answers

0
votes

There is no good reason to declare method as returning Call<ResponseBody> if you are using RxJava anyway. Declare it as Single<ResponseBody> and use its result directly.