I have a method that returns an Observable, which are ids of some Items. I\'d like to go through this list and download every Item
Use a Transformer that modifies the source Observable, calling a flatMap on it with a function. You can think of this as a 2-step process:
Iterable) and re-emits it as an ObservableflatMap takes each of these emitted Observable objects an merges them into a single ObservableThe Transformer looks like this:
public class FlattenTransform implements Observable.Transformer, T> {
@Override
public Observable extends T> call(Observable extends Iterable> source) {
return source.flatMap(new Func1, Observable>() {
@Override
public Observable call(Iterable values) {
return Observable.from(values);
}
});
}
}
Once you've created your Transformer, you can use compose to apply the transformation on the source observable:
public class Example {
private static final ArrayList sourceList = new ArrayList<>(Arrays.asList(new Long[] {1L,2L,3L}));
private static final Observable> listObservable = Observable.just(sourceList);
private static final FlattenTransform flattenList = new FlattenTransform();
public static void main(String[] args) {
listObservable.compose(flattenList).subscribe(printItem);
}
private static Action1 printItem = new Action1() {
@Override
public void call(Long item) {
System.out.println("item: " + item);
}
};
}
The advantage of using a compose with a Transformer instead of a flatMap with a Func1 is that if in the future if you need to flatten a list again, you won't even have to think about which operator to use (map? flatMap? concatMap?). In other words, the flatmap operation is baked into the FlattenTransform class and that detail is abstracted away.
Transformers also have other benefits, such as being able to chain together multiple operations.