RXJava组合了多个订阅



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

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

模型如下

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。合并,但这似乎是有希望的,因为它不允许我保持订阅代码从一个庞大的处理程序分开。有人有什么建议吗?


其中一种选择是使用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));
            }
        }
    });

相关内容

  • 没有找到相关文章

最新更新