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); } });