我是RxJava编程的新手,需要帮助才能处理我的代码问题。我有以下代码:
public Single<List<Modifications>> loadModificationsImages() {
return Observable.fromCallable(DataStoreRepository::loadModifications)
.subscribeOn(Schedulers.io())
.flatMapIterable(list -> list)
.doOnNext(item -> {
Observable.fromIterable(item.images)
.forEach(image -> {
ApiRepository.getModificationsImages(item.id, image.id)
.subscribeOn(Schedulers.computation())
.retry(3)
.subscribe(response -> {
InputStream is = response.byteStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
String contentSubType = response.contentType().subtype();
String fileName = "modifications_id_" + item.id + "_image_id_" + image.id + "." + contentSubType;
FileUtil.saveBitmap(bitmap, fileName);
Modifications.Images img = new Modifications.Images(image.id, fileName, image.type);
DataStoreRepository.updateModificationsImage(img, item.id);
});
});
})
.toList();
}
它完美无缺,但我需要将每个Modifications.Images
收集到一个集合中,并将其传递给方法(DataStoreRepository.updateListOfModificationsImage(List<Modifications.Images> images, int id)
)以更新数据库。所以,这一行的问题是:
Modifications.Images img = new Modifications.Images(image.id, fileName, image.type);
DataStoreRepository.updateModificationsImage(img, item.id);
它只是使用单个项目覆盖数据库中的记录。我试图通过应用Collection修改给定的代码,但它对我不起作用。
感谢您的帮助!
答案 0 :(得分:2)
在回调中订阅几乎总是错误的。否则,您应该toList
图像,然后调用批量更新方法:
public Single<List<Modifications>> loadModificationsImages() {
return Observable.fromCallable(DataStoreRepository::loadModifications)
.subscribeOn(Schedulers.io())
.flatMapIterable(list -> list)
.flatMapSingle(item ->
Observable.fromIterable(item.images)
.flatMap(image ->
ApiRepository.getModificationsImages(item.id, image.id)
.subscribeOn(Schedulers.io())
.retry(3)
.map(response -> {
InputStream is = response.byteStream();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
String contentSubType = response.contentType().subtype();
String fileName = "modifications_id_" + item.id + "_image_id_"
+ image.id + "." + contentSubType;
FileUtil.saveBitmap(bitmap, fileName);
Modifications.Images img = new Modifications.Images(
image.id, fileName, image.type);
return img;
})
)
.toList()
.doOnSuccess(images ->
DataStoreRepository.updateListOfModificationsImage(images, image.id)
)
);
}