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

戏子无情 提交于 2019-12-03 06:05:21

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.

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.

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