【问题标题】:retrofit call execute using rxjava使用 rxjava 执行改造调用
【发布时间】: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());,但没有按预期工作。

【问题讨论】:

    标签: android rx-java retrofit2


    【解决方案1】:

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

    【讨论】:

    • 我不想要直接响应对象。我想逐字节下载文件。单一接口将返回包含文件对象的单一主体。
    • 确实,我错过了你的意思。我在 RxSwift 中有一个类似的例子,也许你可以从中得到一些与 RxJava 一起使用的东西 - github.com/maxvol/RxOnDemandResources/blob/master/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2016-11-24
    • 2020-11-11
    相关资源
    最近更新 更多