use*_*102 4 android rx-java okhttp okio rx-android
我正在尝试使用 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);
}
Run Code Online (Sandbox Code Playgroud)
有谁知道是什么原因导致速度变慢,或者我是否错误地使用了操作员?
使用 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));
}
Run Code Online (Sandbox Code Playgroud)
我们使用 flatMap 上的 maxConcurrent 限制每个订阅者的同时请求数。
| 归档时间: |
|
| 查看次数: |
6419 次 |
| 最近记录: |