prometheuspk prometheuspk - 1 year ago 101
Android Question

How to send onError if result is invalid in RxJava

I have implemented a POJO like so.

public class WebResponse<T> {

private String Response;
private String Message;
private T Result;

As an example if
is success, I will receive an Array of countries in

To perform composition operations on the
s only I
'd the WebResponse and applied the relevant operators. Like so:

Observable<WebResponse<ArrayList<Country>>> countryListAsObservable = api.getCountryListAsObservable();
new Func1<WebResponse<ArrayList<Country>>, Observable<?>>() {
public Observable<Country> call(WebResponse<ArrayList<Country>> arrayListWebResponse) {

return Observable.from(arrayListWebResponse.getResult());
.map(new Func1<Country, String>() {
public String call(Country country) {
return country.getName();
new Action1<String>() {
public void call(String o) {
Log.i("Country name", o);

Now there is a chance that the server itself will send failure which will be in
. When this occurs I want to trigger the

How can I do that without breaking the chain?

Answer Source

Have you tried something like the code below?

countryListAsObservable.flatMap(new Func1<WebResponse<ArrayList<Country>>, Observable<?>>() {
    public Observable<Country> call(final WebResponse<ArrayList<Country>> response) {
        if (!isValidResponse(response)) {
            return Observable.error(new Exception("Response is invalid"));
        } else {
            return Observable.from(response.getResult());

    public boolean isValidResponse(final WebResponse<ArrayList<Country>> response) {
        return response != null && response.getResult() != null;

The idea is to modify flatMap function a bit and return an Observable.error if the response isn't valid.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download