如何使用带有已检查异常的Observable.fromCallable()? [英] How to use Observable.fromCallable() with a checked Exception?
问题描述
Observable.fromCallable()
非常适合将单个函数转换为Observable。但是你如何处理函数可能抛出的已检查异常?
Observable.fromCallable()
is great for converting a single function into an Observable. But how do you handle checked exceptions that might be thrown by the function?
我见过的大多数例子都使用lambdas和just work。但是如果没有lambda,你会怎么做?例如,请参阅这篇精彩的文章中的引用:
Most of the examples I've seen use lambdas and "just work". But how would you do this without lambdas? For example, see the quote below from this great article:
Observable.fromCallable(() -> downloadFileFromNetwork());
现在这是一个单线程!它处理已检查的异常,没有更奇怪的Observable.just()和Observable.error()用于延迟代码执行这样简单的事情!
It's a one-liner now! It deals with checked exceptions, no more weird Observable.just() and Observable.error() for such easy thing as deferring code execution!
<当我尝试在没有lambda表达式的情况下实现上面的Observable时,基于我见过的其他示例,以及Android Studio如何自动完成,我得到以下结果:
When I attempt to implement the above Observable without a lambda expression, based on other examples I've seen, and how Android Studio auto-completes, I get the following:
Observable.fromCallable(new Func0<File>() {
@Override
public File call() {
return downloadFileFromNetwork();
}
}
但是如果 downloadFileFromNetwork()
抛出一个已检查的异常,我必须尝试捕获它并将其包装在 RuntimeException
中。必须有一个更好的方法!上面的lambda如何支持这个?!?!
But if downloadFileFromNetwork()
throws a checked exception, I have to try-catch it and wrap it in a RuntimeException
. There's got to be a better way! How does the above lambda support this?!?!
推荐答案
而不是使用 Func0
Observable.fromCallable()
,使用 Callable
。例如:
Rather than using a Func0
with Observable.fromCallable()
, use Callable
. For example:
Observable.fromCallable(new Callable<File>() {
@Override
public File call() throws Exception {
return downloadFileFromNetwork();
}
}
由于可赎回
的方法 call()
throws Exception
,你不必将你的函数包装成一个试着抓!这必须是lambda在引擎盖下使用的内容。
Since Callable
's method call()
throws Exception
, you don't have to wrap your function in a try-catch! This must be what the lambda is using under the hood.
这篇关于如何使用带有已检查异常的Observable.fromCallable()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!