我尝试使用OkHttp下载文件并使用Okio写入磁盘。此外,我还为此过程创建了一个rx observable。它工作正常,但它明显慢于我之前使用的(Koush的离子库)。
以下是我创建observable的方法:
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);
}
有谁知道可能导致速度慢的原因,或者我是否错误地使用了运算符?
答案 0 :(得分:4)
使用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限制每个订阅者的同时请求数。