【发布时间】:2018-02-05 08:43:11
【问题描述】:
场景:
-
创建请求
**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 中移植以上代码。
我想要的只是出于某种目的逐字节下载文件。
我尝试在正在进行的异步操作 (RxJava) 中调用 downloadFile(request.execute().body());,但没有按预期工作。
【问题讨论】: