Rxjava实践之路[入门篇]

前言

Github Rxjava主页是这样描述:a library for composing asynchronous and event-based programs using observable sequences for the Java VM(一个在 Java VM 上使用可观测的序列来组成异步的、基于事件的程序的库)。说白了,Rxjava就是一个实现异步操作的库,用来取代AsynTask、handler + Thread等。之所以越来越多的开发者崇尚Rxjava技术,其中最主要的原因在于其简洁,随着程序逻辑变得越来越复杂,它依然能够保持简洁。RxJava 的异步实现,是通过一种扩展的观察者模式来实现的。关于Rxjava详细原理就不讲解了,因为这个意义并不是太大,如何上手使用才是王道!

Usage

此处我只针对android studio开发做讲解,谢谢大家理解。
首先引入依赖库如下:

dependencies {
    compile 'io.reactivex:rxjava:1.0.14'
    compile 'io.reactivex:rxandroid:1.0.1'
}

接下来抛砖如玉做基本使用总结。
有了解过Rxjava的童鞋应该知道Rxjava主要由三部分组成:Observable(被观察者)、Subscriber(观察者)、subscribe(订阅)。被观察者通过订阅被观察者所观察,观察者通过订阅第一时间熟知被观察者的一举一动。接下来讲解一下有那些创建Observable(被观察者)的方式,以及这些Observable的作用。

1、create observable

    /**
     * create Observable
     * @author leibing
     * @createTime 2016/09/13
     * @lastModify 2016/09/13
     * @param
     * @return
     */
    private void createObservable() {
        // 通过create创建observable对象,在call中调用subscriber的onnext方法
        Observable observable = Observable.create(new Observable.OnSubscribe() {
            @Override
            public void call(Subscriber subscriber) {
                for (int i = 0; i < 20; i++) {
                    subscriber.onNext("i = " + i);
                }
                subscriber.onCompleted();
            }
        });
        // 上面的代码我们已经构建了一个观察者,我们接下来新建一个订阅者
        Subscriber subscriber = new Subscriber() {
            @Override
            public void onCompleted() {
                System.out.println("dddddddddddd create complete");
            }

            @Override
            public void onError(Throwable e) {
                System.out.println("ddddddddddd create error");
            }

            @Override
            public void onNext(String s) {
                System.out.println("dddddddddddd  create " + s);
            }
        };
        // 通过调用subscribe方法使观察者和订阅者产生关联,一旦订阅就观察者就开始发送消息
        observable.subscribe(subscriber);
    }

运行结果如下:

 09-18 11:07:36.462 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 0
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 1
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 2
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 3
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 4
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 5
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 6
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 7
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 8
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 9
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 10
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 11
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 12
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 13
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 14
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 15
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 16
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 17
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 18
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd  create i = 19
09-18 11:07:36.463 27973-27973/cn.jianke.rxjavademo I/System.out: dddddddddddd create complete

2、 just observable

    /**
     * 根据图片的url路径获得Bitmap对象
     * @author leibing
     * @createTime 2016/09/17
     * @lastModify 2016/09/17
     * @param url
     * @return
     */
    private Bitmap returnBitmap(String url) {
        URL fileUrl = null;
        Bitmap bitmap = null;
        try {
            fileUrl = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) fileUrl
                    .openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 用map变换字符串为bitmap
     * @author leibing
     * @createTime 2016/09/17
     * @lastModify 2016/09/17
     * @param
     * @return
     */
    private void justShowImg() {
        mProgressSwip.setRefreshing(true);
        // 图片地址
        String url = "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&" +
                "quality=100&size=b4000_4000&sec=1474106737&di=8432956a8f4868587" +
                "5f64ca01246f81f&src=http://g.hiphotos.baidu.com/imgad/pic/item/" +
                "f603918fa0ec08fa9f0b7dd85eee3d6d55fbda42.jpg";
        // map变换将url转换成bitmap
        Observable.just(url).map(new Func1() {
            @Override
            public Bitmap call(String s) {
                // 通过url拿去bitmap
                return returnBitmap(s);
            }
        }).subscribeOn(Schedulers.io()). // 订阅在io线程
                observeOn(AndroidSchedulers.mainThread()) //发送在UI线程(处理更新UI)
                .subscribe(new Action1() {
                    @Override
                    public void call(Bitmap bitmap) {
                        // 发送后处理更新UI
                        mProgressSwip.setRefreshing(false);
                        showIv.setImageBitmap(bitmap);
                    }
                });
    }

运行结果如下:

Rxjava实践之路[入门篇]_第1张图片
just.gif

3、from observable

    /**
     * 集合操作
     * @author leibing
     * @createTime 2016/09/18
     * @lastModify 2016/09/18
     * @param
     * @return
     */
    private void fromObservable() {
        List fromList = new ArrayList<>();
        fromList.add("1");
        fromList.add("2");
        fromList.add("3");
        Observable.from(fromList).subscribe(new Action1() {
            @Override
            public void call(String s) {
                System.out.println("ddddddddddddddd from s = " + s);
            }
        });
    }

运行结果如下:

09-18 11:40:46.716 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddd from s = 1
09-18 11:40:46.716 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddd from s = 2
09-18 11:40:46.716 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddd from s = 3

4、 repeat observable

    /**
     * 重复操作
     * @author leibing
     * @createTime 2016/09/08
     * @lastModify 2016/09/08
     * @param
     * @return
     */
    private void repeatObservable(){
        List integers = new ArrayList<>();
        integers.add(0);
        integers.add(1);
        integers.add(2);
        integers.add(3);
        Observable.from(integers).repeat(2).subscribe(new Action1() {
            @Override
            public void call(Integer integer) {
                System.out.println("ddddddddddddddddddd repeat integer = " + integer);
            }
        });
    }

运行结果如下:

09-18 11:42:44.486 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 0
09-18 11:42:44.486 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 1
09-18 11:42:44.486 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 2
09-18 11:42:44.486 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 3
09-18 11:42:44.487 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 0
09-18 11:42:44.487 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 1
09-18 11:42:44.487 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 2
09-18 11:42:44.487 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddddd repeat integer = 3

5、range observable

    /**
     * 范围操作
     * @author leibing
     * @createTime 2016/09/18
     * @lastModify 2016/09/18
     * @param
     * @return
     */
    private void rangeObservable() {
        // 从指定的数字x开始发射n个数字
        Observable.range(15, 5).subscribe(new Action1() {
            @Override
            public void call(Integer integer) {
                System.out.println("ddddddddddddddddd range integer = " + integer);
            }
        });
    }

运行结果如下:

09-18 11:44:06.424 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd range integer = 15
09-18 11:44:06.426 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd range integer = 16
09-18 11:44:06.426 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd range integer = 17
09-18 11:44:06.427 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd range integer = 18
09-18 11:44:06.428 27973-27973/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd range integer = 19

6、interval observable


    /**
     * 轮询操作
     * @author leibing
     * @createTime 2016/09/18
     * @lastModify 2016/09/18
     * @param
     * @return
     */
    private void intervalObservable() {
        // 指定轮询时间(第一个参数)为x,轮询时间单位(第二个参数)为n开始轮询处理事件.
        Observable.interval(2, TimeUnit.SECONDS).subscribe(new Action1() {
            @Override
            public void call(Long aLong) {
                System.out.println("ddddddddddddddddd interval aLong = " + aLong);
            }
        });
    }

运行结果如下:

09-18 11:45:22.599 27973-20494/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd interval aLong = 0
09-18 11:45:24.600 27973-20494/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd interval aLong = 1
09-18 11:45:26.600 27973-20494/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd interval aLong = 2
                                                                  
                                                                  [ 09-18 11:45:26.610   245:0xf5 I/         ]
                                                                  [BWC INFO](245): get_bwc_mm_property success
09-18 11:45:28.600 27973-20494/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd interval aLong = 3
                                                                  
                                                                  [ 09-18 11:45:28.724   245:0xf5 I/         ]
                                                                  [BWC INFO](245): get_bwc_mm_property success
09-18 11:45:30.599 27973-20494/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd interval aLong = 4
09-18 11:45:32.600 27973-20494/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd interval aLong = 5

7、timer observable

    /**
     * 定时器操作
     * @author leibing
     * @createTime 2016/09/18
     * @lastModify 2016/09/18
     * @param
     * @return
     */
    private void timerObservable() {
        // 指定一定时间后才发射
        Observable.timer(4, TimeUnit.SECONDS).subscribe(new Action1() {
            @Override
            public void call(Long aLong) {
                System.out.println("ddddddddddddddddd timer along = " + aLong);
            }
        });
    }

运行结果如下:

09-18 11:49:31.393 22687-22756/cn.jianke.rxjavademo I/System.out: ddddddddddddddddd timer along = 0

总结

Rxjava最基本用法已做介绍,相信大家对Rxjava有了初步的理解,看那么多通篇大论,还不如自己动手写demo测试验证,多看看,多写写,大家一起进步,文章写得一般,俗气,只为更好地理解。欢迎大家拍砖!
demo地址:RxjavaDemo

作者

你可能感兴趣的:(Rxjava实践之路[入门篇])