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;
}
}
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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With