我从数据库中获取音乐文件列表
public Flowable<List<MusicFile>> getMusicFiles() {
return database.musicDao().getMusicFiles();
}
另外,我有一个从存储中下载单个文件的方法(实现实际上并不重要):
public Completable downloadFile(MusicFile musicFile) {
String fileKey = musicFile.getFileName();
File toFile = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/" + fileKey);
return Completable.create(e -> transferUtility.download(AWS_S3_BUCKET, fileKey, toFile)
.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if (TransferState.COMPLETED.equals(state)) {
e.onComplete();
}
}
//...
);
}
我有一个解决方案,但它看起来很丑陋
private List<MusicFile> cache;
@Override
public Flowable<List<MusicFile>> getMusicFiles() {
return database.musicDao().getMusicFiles()
.flatMapCompletable(new Function<List<MusicFile>, CompletableSource>() {
@Override
public CompletableSource apply(List<MusicFile> musicFiles) throws Exception {
cache = musicFiles;
int tracksAmount = musicFiles.size();
List<Completable> downloadTasks = new ArrayList<Completable>(tracksAmount);
for (int i = 0; i < tracksAmount; i++) {
downloadTasks.add(aws.downloadFile(musicFiles.get(i)));
}
return Completable.merge(downloadTasks);
}
}).toFlowable().flatMap(o -> Flowable.just(cache));
}
是否可以避免缓存文件而只是等待每个文件加载?