如何并行执行observable列表并收集结果

时间:2017-12-11 21:08:48

标签: rx-java rx-android

如果有一个Observable列表,例如:

Observable<Msg> obs1 = getObs1();
Observable<Msg> obs2 = getObs2();

List<Observable<Msg>> listOfObs = new ArrayList<Observable<Msg>>();
listOfObs.add(obs1);
listOfObs.add(obs2);

Observabke allObs = Observable.zip(observableListOfEntries, new FuncN<List<Message2>>() {
        @Override
        public List<Msg> call(Object... args) {
            List<Msg> message2List = new ArrayList<Msg>();
            for (Object obj : args) {
                message2List.add((Message2) obj);
                Log.d("Msg>>>", ((Msg) obj).getMsg());
            }
            return message2List;
        }
    });

我使用了previouse代码,但似乎有错误,因为日志消息从未打印过。我该怎么做才能执行列表中的所有observable?

1 个答案:

答案 0 :(得分:2)

    Observable<Msg> obs1 = getObs1();
    Observable<Msg> obs2 = getObs2();

    List<Observable<Msg>> listOfObs = new ArrayList<Observable<Msg>>();
    listOfObs.add(obs1.subscribeOn(Schedulers.io()));
    listOfObs.add(obs2.subscribeOn(Schedulers.io()));

    Observable allObs = Observable.zip(listOfObs, new FuncN<List<Msg>>() {
        @Override
        public List<Msg> call(Object... args) {
            List<Msg> message2List = new ArrayList<Msg>();
            for (Object obj : args) {
                message2List.add((Msg) obj);
                Log.d("Msg>>>", ((Msg) obj).getMsg());
            }
            return message2List;
        }
    });
    allObs.toBlocking().single();