我想這樣做:如何處理在地圖中的異常()可觀察的RxJava
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()
方法,它可以拋出異常。我如何讓觀察者在onError()
中處理它。或者,這不是考慮這個問題的正確方法嗎?
請注意,在像RxJava 2這樣的運算符中,'map'允許從lambda中引發已檢查的異常。這實際上是RxJava 1中的一個設計缺陷,因爲拋出的確切錯誤無法在映射lambda中的'onError'中傳播,而不會被包裝爲'RuntimeException'。 –