如何在RxJava中的Observable中处理map()中的异常
发布时间:2020-09-25 15:31:41 所属栏目:Java 来源:互联网
导读:我想这样做: Observable.just(bitmap) .map(new Func1Bitmap, File() { @Override public File call(Bitmap photoBitmap) { //File creation throws
|
我想这样做: Observable.just(bitmap)
.map(new Func1<Bitmap,File>() {
@Override
public File call(Bitmap photoBitmap) {
//File creation throws IOException,//I just want it to hit the onError() inside subscribe()
File photoFile = new File(App.getAppContext().getCacheDir(),"userprofilepic_temp.jpg");
if(photoFile.isFile()) {//delete the file first if it exists otherwise the new file won't be created
photoFile.delete();
}
photoFile.createNewFile(); //saves the file in the cache dir
FileOutputStream fos = new FileOutputStream(photoFile);
photoBitmap.compress(Bitmap.CompressFormat.JPEG,90,fos);//jpeg format
fos.close();
return photoFile;
}
})
.subscribe(//continue implementation...);
基本上在call()方法中,它可以抛出异常.如何使Observer在onError()中处理它.或者这不是正确的思考方式吗? 解决方法rx将始终捕获错误,即使这是RuntimeException.所以你可以在catch块中抛出一些类型的运行时异常.这实际上应该是如何工作的. Observable.just(bitmap)
.map(b -> {
try {
// do some work which throws IOException
throw new IOException("something went wrong");
} catch (IOException e) {
throw new RXIOException(e);
// Or you can use
throw Exceptions.propagate(e);
// This helper method will wrap your exception with runtime one
}
}).subscribe(o -> {
// do something here
},exception -> exception.printStackTrace());
public static class RXIOException extends RuntimeException {
public RXIOException(IOException throwable) {
super(throwable);
}
} (编辑:鄂州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
