Java 如何在Android上使用反应式扩展下载带有进度更新的文件

Java 如何在Android上使用反应式扩展下载带有进度更新的文件,java,android,rx-java,lifecycle,okhttp,Java,Android,Rx Java,Lifecycle,Okhttp,我目前正在编写一个需要进行大量api调用组合的应用程序,因此第一次使用rxjava,因为它似乎更便于处理异步事件和Android生命周期 不过,该应用程序有时还需要加载打包在zip存档中的静态数据集。为了保持一致性,我尝试使用rx进行此操作,它工作得很好,但我没有真正掌握如何订阅进度事件以使用文件下载进度更新UI 这是我现在用来下载使用okhttp库的文件的代码: downloadService.downloadFile(filename) .flatMap(new Func1<R

我目前正在编写一个需要进行大量api调用组合的应用程序,因此第一次使用rxjava,因为它似乎更便于处理异步事件和Android生命周期

不过,该应用程序有时还需要加载打包在zip存档中的静态数据集。为了保持一致性,我尝试使用rx进行此操作,它工作得很好,但我没有真正掌握如何订阅进度事件以使用文件下载进度更新UI

这是我现在用来下载使用okhttp库的文件的代码:

downloadService.downloadFile(filename)
    .flatMap(new Func1<Response<ResponseBody>, Observable<File>>()
    {
        @Override
        public Observable<File> call(final Response<ResponseBody> responseBodyResponse)
        {
            return Observable.create(new Observable.OnSubscribe<File>()
            {
                @Override
                public void call(Subscriber<? super File> subscriber)
                {
                    try
                    {
                        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), filename);
                        BufferedSink sink = Okio.buffer(Okio.sink(file));
                        sink.writeAll(responseBodyResponse.body().source());
                        sink.close();
                        subscriber.onNext(file);
                        subscriber.onCompleted();
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                        subscriber.onError(e);
                    }
                }
            });
        }
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<File>()
    {
        @Override
        public void onCompleted()
        {
            Log.d("downloadZipFile", "onCompleted");
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            Log.d("downloadZipFile", "Error " + e.getMessage());
        }

        @Override
        public void onNext(File file) {
            Log.d("downloadZipFile", "File downloaded to " + file.getAbsolutePath());
        }
    });
downloadService.downloadFile(文件名)
.flatMap(新函数1()
{
@凌驾
公共可观察呼叫(最终响应-响应-响应)
{
返回Observable.create(newobservable.OnSubscribe()
{
@凌驾

public void call(订阅方首先:永远不要使用
Observable.create()
,除非您知道自己在做什么,并且准备好处理背压和Observable应该处理的所有事情。(更新:如果您使用RxJava2,您可以安全地使用
create()
方法)

也就是说,首先创建一个类来保存进度信息

public class DownloadProgress<DATA> {
    private final float progress;
    private final DATA data;

    public DownloadProgress(float progress) {
        this.progress = progress;
        this.data = null;
    }

    public DownloadProgress(@NonNull DATA data) {
        this.progress = 1f;
        this.data = data;
    }

    public float getProgress() {
        return progress;
    }

    public boolean isDone() {
        return data != null;
    }

    public DATA getData() {
        return data;
    }
}
这应该可以工作(我没有测试过),但如果您取消订阅,它不会让您取消正在进行的http调用

如果您可以修改您的下载服务,我宁愿通过OkHttp来处理它,其灵感来自配方示例:

用法:

    String filename = "yourFileName";
    String url = "http://your.url.here";
    File saveLocation = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), filename);
    downloadFile(url, saveLocation)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(fileDownloadProgress -> {
                float progress = fileDownloadProgress.getProgress();
                // TODO update UI
            })
            .filter(DownloadProgress::isDone)
            .map(DownloadProgress::getData)
            .subscribe(file -> {
                // file downloaded
            }, throwable -> {
                // error
            });

哇,非常感谢您花时间提供如此详细的示例。谢谢。@Markus您能为上述答案发布工作示例吗?这将非常有用。有人使用此解决方案吗?看起来非常棒。谢谢@Markus!一些更新:RxJava2 create方法的工作原理类似于
fromEmitter()
很好。我很遗憾我建议使用
doOnNext()
:在订阅时处理一切。如果你需要单独处理进度和完成,请使用
share()
并使用合适的筛选器订阅两次。顺便说一句,我编辑了帖子:
onError
应该是
tryOnError()
。否则,它可能会在处理下游时尝试发出错误,从而导致异常无法传递和->崩溃。
    String filename = "yourFileName";
    downloadFile(filename)
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(fileDownloadProgress -> {
                float progress = fileDownloadProgress.getProgress();
                // TODO update UI
            })
            .filter(DownloadProgress::isDone)
            .map(DownloadProgress::getData)
            .subscribe(file -> {
                // file downloaded
            }, throwable -> {
                // error
            });
public Observable<DownloadProgress<File>> downloadFile(@NonNull final String url, @NonNull final File saveLocation) {
    return Observable.fromEmitter(emitter -> {
        Request request = new Request.Builder()
                .url(url)
                .build();

        final ProgressListener progressListener = (bytesRead, contentLength, done) -> {
            // range [0,1]
            float progress = done ? 1f : (float) bytesRead / contentLength;
            emitter.onNext(new DownloadProgress<>(progress));
        };

        OkHttpClient client = new OkHttpClient.Builder()
                .addNetworkInterceptor(chain -> {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder()
                            .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                            .build();
                })
                .build();

        final Call call = client.newCall(request);
        emitter.setCancellation(() -> call.cancel());

        try {
            Response response = call.execute();
            BufferedSink sink = Okio.buffer(Okio.sink(saveLocation));
            sink.writeAll(response.body().source());
            sink.close();
            emitter.onNext(new DownloadProgress<>(saveLocation));
            emitter.onCompleted();
        } catch (IOException e) {
            emitter.onError(e);
        }
    }, Emitter.BackpressureMode.LATEST);
}
public static class ProgressResponseBody extends ResponseBody {

    private final ResponseBody responseBody;
    private final ProgressListener progressListener;
    private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // read() returns the number of bytes read, or -1 if this source is exhausted.
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }
}

interface ProgressListener {
    void update(long bytesRead, long contentLength, boolean done);
}
    String filename = "yourFileName";
    String url = "http://your.url.here";
    File saveLocation = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsoluteFile(), filename);
    downloadFile(url, saveLocation)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(fileDownloadProgress -> {
                float progress = fileDownloadProgress.getProgress();
                // TODO update UI
            })
            .filter(DownloadProgress::isDone)
            .map(DownloadProgress::getData)
            .subscribe(file -> {
                // file downloaded
            }, throwable -> {
                // error
            });