繁体   English   中英

使用rxjava执行改造调用

[英]retrofit call execute using rxjava

场景:

  • 建立要求

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

问题

我无法使用Observable / Single接口在RxJava移植以上代码。 我想要的只是出于某种目的逐字节下载文件。

我试图调用downloadFile(request.execute().body()); 内部正在进行的异步操作(RxJava)中,但未按预期工作。

如果您仍在使用RxJava,则没有充分的理由将方法声明为返回Call <ResponseBody> 将其声明为Single <ResponseBody>并直接使用其结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM