RxJava2.0之map和flatMap操作符的区别

概述

  1. flatMap将一个发送事件的上游Observable变换为多个发送事件的Observables,然后将它们发射的事件合并后放进一个单独的Observable里.
  2. flatMap并不保证事件的顺序,如果要保证事件的顺序,使用concatMap.

代码

public class Demo {
    public static void main(String[] args) {
        log("hello");

        Observable.just(1, 2, 3).map(new Function<Integer, String>() {

            @Override
            public String apply(Integer integer) throws Exception {
                return "" + integer;
            }
        }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                log(s);
            }
        });

        Observable.just(1, 2, 3).flatMap(new Function<Integer, ObservableSource<String>>() {
            @Override
            public ObservableSource<String> apply(Integer integer) throws Exception {
                final List<String> list = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    list.add("I am value " + integer + ", i = " + i);
                }
                return Observable.fromIterable(list);
            }
        }).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                log(s);
            }
        });

    }

    private static void log(String s) {
        System.out.println(s);
    }
}

运行结果:

hello
1
2
3
I am value 1, i = 0
I am value 1, i = 1
I am value 1, i = 2
I am value 2, i = 0
I am value 2, i = 1
I am value 2, i = 2
I am value 3, i = 0
I am value 3, i = 1
I am value 3, i = 2

flatMap接受的参数Function对象中,实现的apply方法的返回类型为ObservableSource,ObservableSource是一个接口,里面只有一个需要实现的方法subscribe,Observable类就实现了该接口,所以apply方法中返回Observable对象即可,这里通过Observable.fromIterable生成Observable对象。

public interface ObservableSource<T> {

    /**
     * Subscribes the given Observer to this ObservableSource instance.
     * @param observer the Observer, not null
     * @throws NullPointerException if {@code observer} is null
     */
    void subscribe(@NonNull Observer<? super T> observer);
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值