I'm trying to do a parallel download of a list of images, combining them to a map.
At first I tried to make an Observable like this:
Observable<Map<Integer, Bitmap>> getImages(final List<Activity> activities) {
return Observable.create(new Observable.OnSubscribe<Map<Integer, Bitmap>>() {
@Override
public void call(Subscriber<? super Map<Integer, Bitmap>> subscriber) {
try {
Map<Integer, Bitmap> result = new HashMap<Integer, Bitmap>();
for (Activity act : activities) {
result.put(act.getId(), downloadImage(act.getImage()));
}
subscriber.onNext(result);
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
This works, but it's not what I want. Because the images are being downloaded sequentially. And I think for-loops are not nice in rxjava. So I created these Observables:
Observable<Bitmap> getImage(final Activity activity) {
return Observable.create(new Observable.OnSubscribe<Bitmap>() {
@Override
public void call(Subscriber<? super Bitmap> subscriber) {
try {
subscriber.onNext(downloadImage(activity.getImage()));
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
Observable<Map<Integer, Bitmap>> getImages(final List<Activity> activities) {
return Observable
.from(activities)
.flatMap(new Func1<Activity, Observable<Bitmap>>() {
@Override
public Observable<Bitmap> call(Activity activity) {
return getImage(activity);
}
})
.toMap(new Func1<Bitmap, Integer>() {
@Override
public Integer call(Bitmap bitmap) {
return 1; // How am I supposed to get the activity.getId()?
}
});
}
So I made an Observable for getting a single image, trying to combine them in the second one using flatMap. This works, but there are still 2 problems:
- When I do a toMap(), how can I retrieve the right id to use as key for the map? I want to use the Activity object for that.
- Unfortunately, the downloads are still beging processed sequentially and not in parallel. How can I fix this?