RxJava - fetch every item on the list

前端 未结 5 421
渐次进展
渐次进展 2020-12-13 08:43

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

5条回答
  •  误落风尘
    2020-12-13 09:28

    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:

    1. The function takes each emitted item (an Iterable) and re-emits it as an Observable
    2. flatMap takes each of these emitted Observable objects an merges them into a single Observable

    The Transformer looks like this:

    public class FlattenTransform implements Observable.Transformer, T> {
        @Override
        public Observable call(Observable> 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.

提交回复
热议问题