Sree Sree - 9 months ago 82
Java Question

How do I handle exceptions in map() in an Observable in RxJava

I want to do this:

.map(new Func1<Bitmap, File>() {
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.createNewFile(); //saves the file in the cache dir

FileOutputStream fos = new FileOutputStream(photoFile);
photoBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);//jpeg format

return photoFile;

.subscribe(//continue implementation...);

Bascially in the
method, it can throw exceptions. How can i make the Observer handle it in
. Or is this not the right way to think about this?

Answer Source

rx will always catch error, even if this is RuntimeException. So you can throw Some kind of Runtime exception in catch block. This is how actually it should work.

                .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.propogate(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) {