在RxJava2

时间:2019-02-02 20:12:35

标签: rx-java2

我正在从2个数据库表中获取值,并在重复删除后基于它们从第三张表中获取值。 我的样本代码是:

db.select("SELECT id from table1 ")
            .getAs(String.class)
            .collectInto(new HashSet<String>(), HashSet::add)
            .zipWith(db.select("SELECT id from table2 ")
                    .getAs(String.class)
                    .collectInto(new HashSet<String>(), HashSet::add),new BiFunction<Set,Set, Single<HashSet<String>>>() {
                        @Override
                        public Single<HashSet<String>> apply(Set t1, Set t2) throws Exception {
                            t1.addAll(t2);

                            return db.select("select useful_data from table3 where id IN ("+AsQuatedString(t1)+").getAs(String.class).collectInto(new HashSet<String>(), HashSet::add);
                        }
                    })/*Point A*/.subscribe(a -> a.subscribe(b -> System.out.println(b)));

所以,问题是在[A点]我得到Single<Single<HashSet>>,我不能得到作为响应休息客户端。

如何将其转换为Single<HashSet>

使用this对于DB连接

1 个答案:

答案 0 :(得分:1)

您的zip文件应返回带有合并集的Single<HashSet>,然后您可以将第二个数据库请求放入flatmap

db.select("SELECT id from table1 ")
        .getAs(String.class)
        .collectInto(new HashSet<String>(), HashSet::add)
        .zipWith(db.select("SELECT id from table2 ")
                .getAs(String.class)
                .collectInto(new HashSet<String>(), HashSet::add), (t1, t2) -> {
                    t1.addAll(t2);
                    return t1;
                })
        .flatMap(concatSet -> {
            // concatSet is a HashMap<String>
            return db.select("select useful_data from table3 where id IN ("+AsQuatedString(concatSet)+")
                    .getAs(String.class)
                    .collectInto(new HashSet<String>(), HashSet::add);
        })
        .subscribe(b -> { // b is a HashMap<String>, result of your second db request.
            System.out.println(b);
        });