zoukankan      html  css  js  c++  java
  • Rxjava2不能再发射Null了

    RxJava2的最大改变就是不能再流里发射Null了,有人会问发射了就怎么了,答案是你的流会因为NPE断开.

    例如下面这段代码因为文件被删了找不到返回null,这时候就不触发下面Consumer的accept。

    Disposable subscribe = Observable.fromCallable(new Callable<Bitmap>() {
                    @Override
                    public Bitmap call() {
                        FileInputStream fis;
                        Bitmap b=null;
                        try {
                            fis = new FileInputStream(path);
                            b = BitmapFactory.decodeStream(fis);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        return b;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) {
                        if (bitmap != null) {
                           viewBc.setImageBitmap(bitmap);
                        } else {
                            viewBc.setImageResource(R.drawable.wallpaper_default);
                        }
                    }
                });

    如果需要处理,则需要处理这种异常Consumer<Throwable>

    Disposable subscribe = Observable.fromCallable(new Callable<Bitmap>() {
                    @Override
                    public Bitmap call() {
                        FileInputStream fis;
                        Bitmap b=null;
                        try {
                            fis = new FileInputStream(path);
                            b = BitmapFactory.decodeStream(fis);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
    
                        }
                        return b;
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Bitmap>() {
                    @Override
                    public void accept(Bitmap bitmap) {
                        if (bitmap != null) {
                           viewBc.setImageBitmap(bitmap);
                        } else {
                            viewBc.setImageResource(R.drawable.wallpaper_default);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        viewBc.setImageResource(R.drawable.wallpaper_default);
                    }
                });
  • 相关阅读:
    游吟诗人阿严
    学霸女
    sql group by 分组后查询最新的一条数据
    腐朽
    我喜欢不说话的山川
    redis启动
    php 时间轴,数据统计(最近7天的数据)
    php options 请求跨域
    mac关机声音
    JVM-内存模型
  • 原文地址:https://www.cnblogs.com/mingfeng002/p/11119338.html
Copyright © 2011-2022 走看看