Rxjava2之rxandroid基本用法

rxAndroid的github地址https://github.com/ReactiveX/RxAndroid 
配置:module下

compile 'io.reactivex.rxjava2:rxandroid:2.0.1'

compile 'io.reactivex.rxjava2:rxjava:2.0.5'
  • 1
  • 2
  • 3

这里主要介绍基本的使用以及Action和Function的一些变动

以下是RxJava的标准使用

private void normalCreate() {
        //创建观察者,subscriber或observer
        Observer<String> observer=new Observer<String>() {
            @Override
            /** * Provides the Observer with the means of cancelling (disposing) the * connection (channel) with the Observable in both * synchronous (from within {@link #onNext(Object)}) and asynchronous manner. * @param d the Disposable instance whose {@link Disposable#dispose()} can * be called anytime to cancel the connection * @since 2.0 */
            public void onSubscribe(Disposable d) {
                //可用于取消订阅
                d.dispose();
                //还可以判断是否处于取消状态
                //boolean b=d.isDisposed();
            }
    //一般需要展示
            @Override
            public void onNext(String s) {
        Log.e("TAG", "onNext: "+s );
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };

        //创建被观察者
        //和RxJava1.0相比,他们都增加了throws Exception,也就是说,在这些方法做某些操作就不需要try-catch 。

        Observable<String> observable=Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            //将事件发射出去,持有观察者的对象
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext("第一次调用");
                e.onNext("第二次调用");
                e.onNext("第三次调用");

                e.onComplete();
            }
        });
//确立订阅关系
        observable.subscribe(observer);
    }
private void mapDemo() {

        //在2.0后命名规则有了改变

        //Action1--------Consumer一个参数的

        //Action2--------BiConsumer两个参数的
        //而Function的也一样
        Observable.just("图片存放路径").map(new Function<String, Bitmap>() {
            @Override
            public Bitmap apply(String s) throws Exception {
                return getBitmapFromFile(s);
            }
        }).subscribeOn(Schedules.io())//指定 subscribe() 事件发送发生在 IO 线程
        .observeOn(AndroidSchedulers.mainThread())//指定 Subscriber 的回调处理发生在主线程
                //这里的Action一个参数的改为COnsumer
                .subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) throws Exception {
                        iv.setImageBitmap(bitmap);
                    }
                });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

apple_51426592

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值