How do I handle exceptions in map() in an Observable in RxJava(如何在RxJava中处理可观察对象的map()中的异常)
                            本文介绍了如何在RxJava中处理可观察对象的map()中的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我要这样做:
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()中处理它。或者这不是思考这件事的正确方式吗?
推荐答案
rx始终会捕获错误,即使这是运行异常。 因此您可以在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);
        }
}
                        这篇关于如何在RxJava中处理可观察对象的map()中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:如何在RxJava中处理可观察对象的map()中的异常
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 从 python 访问 JVM 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				