小编Mar*_*us 的帖子

如何使用Android上的响应式扩展下载包含进度更新的文件

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

但是,应用程序有时还需要加载打包在zip存档中的静态数据集.我尝试使用rx进行此操作以及一致性并且它运行良好,但我真的没有掌握如何订阅progress-events以使用文件下载进度更新UI.

这是我现在使用的代码,用于下载使用okhttp-library的文件:

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()); …
Run Code Online (Sandbox Code Playgroud)

java lifecycle android rx-java okhttp

2
推荐指数
1
解决办法
3778
查看次数

标签 统计

android ×1

java ×1

lifecycle ×1

okhttp ×1

rx-java ×1