RxJava2将两个Flowables合并成一个

5

我很难找到任何将两个Flowables合并成一个的RxJava2示例。

我正在尝试修改这个测试,加入类似于以下内容:

    Integer[] ints = new Integer[count];
    Integer[] moreints = new Integer[count];
    Arrays.fill(ints, 777);
    Arrays.fill(moreints, 777);

    Flowable<Integer> source = Flowable.fromArray(ints);
    Flowable<Integer> anothersource = Flowable.fromArray(moreints);

    Flowable<Integer> zippedsources = Flowable.zip(source, anothersource,
            new BiFunction<Flowable<Integer>, Flowable<Integer>, Flowable<Integer>>() {

                @Override
                public void apply(Flowable<Integer> arg0, Flowable<Integer> arg1) throws Exception {
                    return arg0.blockingFirst() + arg1.blockingLast();
                }

    }).runOn(Schedulers.computation()).map(this).sequential();

编辑:我试图从源和另一个源中获取一个整数并将它们相加,但它似乎与 RxJava1 的做法有根本的不同...... 我尝试了许多变化,返回 Integer、Publisher、Flowable 和 void,但在 zip 运算符本身上仍然会出现错误。

我无法弄清楚在 .zip(Iterable<? extends Publisher<? extends T>>, Function<? super Object[], ? extends R>) 中应该放置什么。


你期望得到什么结果?目前你有什么结果? - Benjamin
尝试使用BiFunction<Integer,Integer,Integer>并调整apply方法的类型。压缩函数不会获取源Flowable,而是每次调用只获取一个值。 - akarnokd
谢谢@akarnokd - 这正是我的误解。 - ChopperOnDick
1个回答

5

如果你只需要压缩两个Flowable,你可以使用Flowable.zipWith操作符。

它的使用方式如下:

source.zipWith(anotherSource, new BiFunction<Integer, Integer, Integer>() {
    @Override public Integer apply(Integer a, Integer b) {
        return a + b;
    } 
};

感谢 BiFunction - CoolMind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接