RxJava2 Flowable collect & collectInto

目录

collect& collectInto接口

collect& collectInto图解

collect& collectInto测试用例

collect& collectInto测试用例分析


collect& collectInto接口

<U> Single<U> collect(Callable<? extends U> initialItemSupplier, BiConsumer<? super U,? superT> collector)

将源Publisher发出的项收集到一个可变数据结构中,并返回发出此结构的Single。

<U> Single<U>

collectInto(U initialItem, BiConsumer<? super U,? super T> collector)

将源Publisher发出的项收集到一个可变数据结构中,并返回发出此结构的Single。

collect& collectInto图解

源码中指向跟reduce使用同样的图解,图上仅仅是单纯的两者相加,但是这里BiFunction函数中可以做更多事情,如果call返回的不是数字,是其他的类型,或者可以做减乘除运算,都是可以的。

RxJava2 Flowable collect & collectInto

 

collect& collectInto测试用例

测试代码
 @Test
    public void collect() {
        Single single = Flowable.just(5, 7, 9).collect(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return 3;
            }
        }, new BiConsumer<Integer, Integer>() {
            @Override
            public void accept(Integer v1, Integer v2) throws Exception {
                //v1是上面call返回的3,v2是冲just中发射的数据
                System.out.println("v1:" + v1 + ",v2:" + v2);
            }
        });

        single.subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer v3) throws Exception {
                //v3是上面call返回的3
                System.out.println("v3:"+v3);
            }
        });

        Flowable.just(30, 80, 90).collectInto(10, new BiConsumer<Integer, Integer>() {
            @Override
            public void accept(Integer v4, Integer v5) throws Exception {
                System.out.println("v4:" + v4 + ",v5:" + v5);
            }
        }).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer v6) throws Exception{
                System.out.println("v6:" + v6);
            }
        });
    }

测试结果:
v1:3,v2:5
v1:3,v2:7
v1:3,v2:9
v3:3
v4:10,v5:30
v4:10,v5:80
v4:10,v5:90
v6:10

 

collect& collectInto测试用例分析

上面同时做了collect& collectInto的测试用例,可以看到,基本上就是第一个参数所生成的值,可以被传递到指定指定BiFunciton函数中,在BiFunciton函数中可以做相应的操作,使用场景比较好把握。