3

所以我有一个我似乎根本无法解决的情况。

我有一种情况,我想并行运行两个网络请求,然后在每个网络请求结束时运行一些代码,然后在每个网络请求处理结束时额外运行。

建模成这样

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 但这似乎很有希望,因为它不允许我将订阅代码与一个大型处理程序分开。有人有建议吗?

4

1 回答 1

8


一种选择是使用 map 对每个响应做额外的工作,然后 zip 加入结果;见例子:

    //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));
            }
        }
    });
于 2014-07-12T14:18:01.707 回答