How to use Observable.fromCallable() with a checked Exception?

99封情书 提交于 2019-12-20 19:36:52

问题


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?

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());

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!

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();
    }
}

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?!?!


回答1:


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();
    }
}

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.




回答2:


You could also do this to return checked exceptions:

return Observable.fromCallable(() -> {
  sharedPreferences.edit()
          .putString(DB_COMPANY, LoganSquare.serialize(
                  CompanyDBTransformation.get(user.getCompany())
          ))
          .apply();
  return user;
  }).onErrorResumeNext(
            throwable -> Observable.error(new CompanySerializationException(throwable))
    );

So here I'm serializing taking the IOException risk, and I'm giving back a more descriptive description.



来源:https://stackoverflow.com/questions/36208331/how-to-use-observable-fromcallable-with-a-checked-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!