gpt4 book ai didi

android - 使用 OkHttp、Okio 和 RxJava 下载文件

转载 作者:行者123 更新时间:2023-11-29 15:51:29 24 4
gpt4 key购买 nike

我正在尝试使用 OkHttp 下载文件并使用 Okio 写入磁盘。我还为这个过程创建了一个 rx observable。它正在运行,但是它明显比我以前使用的(Koush 的 Ion 库)慢。

下面是我如何创建可观察对象:

public Observable<FilesWrapper> download(List<Thing> things) {
return Observable.from(things)
.map(thing -> {
File file = new File(getExternalCacheDir() + File.separator + thing.getName());

if (!file.exists()) {
Request request = new Request.Builder().url(thing.getUrl()).build();
Response response;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()) new IOException();
else {
BufferedSink sink = Okio.buffer(Okio.sink(file));
sink.writeAll(response.body().source());
sink.close();
}
} catch (IOException e) {
new IOException();
}
}

return file;
})
.toList()
.map(files -> new FilesWrapper(files);
}

有谁知道可能导致速度慢的原因,或者我是否使用了不正确的运算符?

最佳答案

使用 flatMap 而不是 map 将允许您并行执行下载:

public Observable<FilesWrapper> download(List<Thing> things) {
return Observable.from(things)
.flatMap(thing -> {
File file = new File(getExternalCacheDir() + File.separator + thing.getName());
if (file.exists()) {
return Observable.just(file);
}

final Observable<File> fileObservable = Observable.create(sub -> {
if (sub.isUnsubscribed()) {
return;
}

Request request = new Request.Builder().url(thing.getUrl()).build();

Response response;
try {
response = client.newCall(request).execute();
if (!response.isSuccessful()) { throw new IOException(); }
} catch (IOException io) {
throw OnErrorThrowable.from(OnErrorThrowable.addValueAsLastCause(io, thing));
}

if (!sub.isUnsubscribed()) {
try (BufferedSink sink = Okio.buffer(Okio.sink(file))) {
sink.writeAll(response.body().source());
} catch (IOException io) {
throw OnErrorThrowable.from(OnErrorThrowable.addValueAsLastCause(io, thing));
}
sub.onNext(file);
sub.onCompleted();
}

});
return fileObservable.subscribeOn(Schedulers.io());
}, 5)
.toList()
.map(files -> new FilesWrapper(files));
}

我们使用 flatMap 上的 maxConcurrent 限制每个订阅者同时请求的数量。

关于android - 使用 OkHttp、Okio 和 RxJava 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com