使用rxjava执行改造调用

时间:2018-02-05 08:43:11

标签: android rx-java retrofit2

场景:

  • 创建请求

    tex
  • 按字节下载字节

    **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();
    }
    

问题

我无法使用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(); } / RxJava接口移植Observable中的代码。 我想要的是为了某种目的按字节下载文件字节。

我试图在正在进行的异步操作(RxJava)中调用Single但是没有按预期工作。

1 个答案:

答案 0 :(得分:0)

如果你正在使用RxJava,没有充分的理由将方法声明为返回 Call&lt; ResponseBody&gt; 。将其声明为 Single&lt; ResponseBody&gt; 并直接使用其结果。