RXJava结合了多个订阅

时间:2014-07-12 03:24:05

标签: java system.reactive rx-java

所以我的情况似乎无法解决。

我遇到这种情况,我希望并行运行两个网络请求,然后在每个网络请求结束时运行一些代码,然后在每个网络请求处理结束时再运行。

模仿这样

GET -> /users (run unique code to this request independently once the request is done)
GET -> /groups (run some unique code to this request independently once the request is done)
Both requests are done, now run some unique code independent of the request processing.

我一直在尝试使用Observable.merge,但这似乎有希望,因为它不允许我将订阅代码与一个大型处理程序分开。有没有人有建议?

1 个答案:

答案 0 :(得分:8)


其中一个选项是使用map对每个响应执行额外的工作,然后压缩以加入结果;见例子:

    //this emulates the first network call
    Observable<List<String>> o1 = Observable.just(Arrays.asList("user1", "user2"));
    //when the data arrives, you may transform it 
    Observable<List<String>> m1 = o1.map(new Func1<List<String>, List<String>>() {
        @Override
        public List<String> call(List<String> users) {
            return users;
        }
    });

    //and the same for the second network call
    Observable<List<String>> o2 = Observable.just(Arrays.asList("group1", "group2"));
    Observable<List<String>> m2 = o2.map(new Func1<List<String>, List<String>>() {
        @Override
        public List<String> call(List<String> groups) {
            return groups;
        }
    });

    //when both network calls succeed you can merge results using zip method    
    Observable<Map<String, List<String>>> result =  Observable.zip(m1, m2, new Func2<List<String>, List<String>, Map<String, List<String>>>() {
        @Override
        public Map<String, List<String>> call(List<String> users, List<String> groups) {
            Map<String, List<String>> result = new HashMap<String, List<String>>();
            for(String user: users){
                result.put(user, groups);
            }
            return result;
        }
    });
    /// now you can return the result


    /// finally you have to subscibe to get the results, e.g:
    result.subscribe(new Action1<Map<String, List<String>>>() {
        @Override
        public void call(Map<String, List<String>> stringListMap) {
            for(String user: stringListMap.keySet()){
                System.out.println("User :"+user+", groups :"+stringListMap.get(user));
            }
        }
    });