【问题标题】:RXJava combining multiple subscriptionsRXJava 结合多个订阅
【发布时间】:2014-07-12 03:24:05
【问题描述】:

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

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

这样建模

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

【问题讨论】:

    标签: java system.reactive rx-java


    【解决方案1】:


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

    【讨论】:

    • 不错的解决方案。基本上需要用到zip,在RXJava群里也找到了。
    • 我有 4 个 API 要组合在 zip 中,每个 API 从服务器返回每 4 个表的字符串中的对象列表。我想使用 gson 库将每个 JSON 列表解析为特定的 ActiveAndroid ORM 类对象并将其保存到 SQLite。如何区分subscribe方法中的每个String响应并根据对象进行解析。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多