rxjava中的异常处理 [英] Exception handling in rxjava
本文介绍了rxjava中的异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试习惯 rxjava
,我试图在Observable中调用下面的 QuoteReader
。我不知道如何处理抛出的异常,
I am trying to get accustomed to rxjava
and I am trying to call the below QuoteReader
in an Observable. I am not sure how to handle the exception thrown,
public class QuoteReader {
public Map<String, Object> getQuote() throws IOException{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url("http://quotes.rest/qod.json").build();
Gson gson = new Gson();
Map<String, Object> responseMap = null;
try(Response response = okHttpClient.newCall(request).execute()) {
responseMap = gson.fromJson(response.body().string(), Map.class);
System.out.println("response map : "+responseMap);
} catch(IOException ioe) {
ioe.printStackTrace();
throw ioe;
} finally {
okHttpClient = null;
request = null;
}
return responseMap;
}
}
以下是我试图写的rx代码,
The following is the rx code I am trying to write,
rx.Observable.just(new QuoteReader().getQuote()) //compile time error saying unhandled exception
.subscribe(System.out::println);
我应该如何更新代码来处理异常。谢谢!
How should I update the code to handle the exception. Thanks!
推荐答案
使用 fromCallable
允许你的方法抛出(加上,它会被懒惰地评估,而不是在你进入Observable世界之前):
Use fromCallable
that allows your method to throw (plus, it gets evaluated lazily and not before you even get into the Observable world):
rx.Observable.fromCallable(() -> new QuoteReader().getQuote())
.subscribe(System.out::println, Throwable::printStackTrace);
这篇关于rxjava中的异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文