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);
                    }
                });
  • 相关阅读:
    .net web开发经典图书总结
    Asp.net Web API实战
    扩展方法之二分查找
    在线转换图片文件等
    如何减少代码中的分支语句
    web插件化解决方案 开发分享
    .NET 4.5 MEF 基于约定的编程模型重典
    所有排序总结(内排序)
    生成zip文件
    open source ESB and integration platform
  • 原文地址:https://www.cnblogs.com/mingfeng002/p/11119338.html
Copyright © 2011-2022 走看看