rxjava android 错误,android - 对RxJava中的错误和异常处理感到困惑 - 堆栈内存溢出...

我刚刚开始学习RxJava,并且已经阅读并观看了很多教程,但是有些事情还没有点击。 我从最底层入手,首先修改了我的应用程序的API调用之一,以返回一个Observable。 当前, AsyncTaskLoader使用该API调用,该AsyncTaskLoader从本地数据库返回缓存的数据,然后进行调用,合并数据并再次返回。 对于我的RxJava实验,这种模式听起来像是一个完美的主题,但是从小开始,我想从我的API调用中返回一个可观察的对象。

这是我最初的电话:

public static ArrayList getStuffForId(String id)

throws IOException, UserNotAuthenticatedException {

Profile profile = getProfile();

HashMap> map = profile.getStuff();

if (map == null) {

throw new IOException("error processing - map cannot be null");

}

return map.get(id);

}

private static Profile getProfile()

throws IOException, UserNotAuthenticatedException {

// <.. getting url auth tokens and other stuff to prepare the request ..>

Response response = sHttpClient.newCall(request).execute();

if (response.code() == ERR_AUTH_REJECTED) {

throw new UserNotAuthenticatedException(response.body().string());

}

if (!response.isSuccessful()) {

throw new IOException("Unexpected code " + response);

}

Gson gson = new Gson();

String result = response.body().string();

response.body().close();

return gson.fromJson(result, Profile.class);

}

在RxJava世界中,我正在考虑以下方面的想法:

public static Observable> getStuffForId(String id) {

return getProfile().map(

Profile::getStuff).map(

map -> {

if (map == null) {

Observable.error(new IOException("error processing - map cannot be null"));

}

return map.get(id);

});

}

private static Observable getProfile() {

return Observable.fromCallable(() -> {

// <.. getting url auth tokens and other stuff to prepare the request ..>

Response response = sHttpClient.newCall(request).execute();

if (response.code() == ERR_AUTH_REJECTED) {

throw new UserNotAuthenticatedException(response.body().string(),

authToken);

}

if (!response.isSuccessful()) {

throw new IOException("Unexpected code " + response);

}

Gson gson = new Gson();

String result = response.body().string();

response.body().close();

return gson.fromJson(result, Profile.class);

});

}

这看起来像人们所期望的吗? 我仍然不确定fromCallable()和defer()之间的区别以及您在哪里使用一个或另一个。 还不确定一旦将异常抛出到fromCallable()方法中后会去哪里-它们会自动以我的订户的onError结尾还是我需要在我的getStuffForId方法中处理它们? 最后,Android Studio警告我, return map.get(id)可能会抛出nullPointer。 仅仅是因为IDE不了解Observable.error将终止执行,还是我不了解Observable.error会发生什么?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值