Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip more than 9 Observables in rxJava

Faced the situation when it is necessary to make 10-12 small parallel queries and combine the results. But if there is a zip method that allows you to combine up to 9 Observables, then how to do more I do not understand. I tried using zip Method

public static <T, R> Observable<R> zip(Iterable<? extends ObservableSource<? extends T>> sources, Function<? super Object[], ? extends R> zipper)

but but got an error

java.lang.ClassCastException: java.util.ArrayList cannot be cast to io.reactivex.ObservableSource

Attempts look like this

List<Observable> list = new ArrayList<>();
list.add(orderRepository.getOne(54, "id"));
list.add(orderRepository.getTwo(54, "id"));
list.add(orderRepository.getThree(54, "id"));
list.add(orderRepository.getFour(54, "id"));
list.add(orderRepository.getFive());
list.add(orderRepository.getSix(54, "id"));
list.add(orderRepository.getSeven(54, "id"));
list.add(orderRepository.getEight());
list.add(orderRepository.getNine());
list.add(orderRepository.getTen(54, "id"));
list.add(orderRepository.getEleven(54, "id"));
Observable.fromIterable(list);

return Observable.zip(list,
        new Function<Object[], OrderModel>() {
            @Override
            public OrderModel apply(Object[] objects) throws Exception {
                Logger.trace("objects = ", objects);
                return new OrderModel();
            }
        });

Please give an example of how to do this in Java or Kotlin.

like image 583
Андрей Avatar asked Aug 20 '18 00:08

Андрей


1 Answers

    Observable one = Observable.zip(
        orderRepository.getOne(54, "id"), 
        orderRepository.getTwo(54, "id"),
        // Etc up to five (I think)
        Function zipper
    );

    Observable two = Observable.zip(
        one, orderRepository.getSix(54, "id"),
        orderRepository.getSeven(54, "id"),
        // Etc up to five,
        Function zipper
    );

Rinse and repeat until you get all your observables zipped together.

like image 158
User42 Avatar answered Sep 19 '22 10:09

User42