prometheuspk prometheuspk - 5 months ago 13
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
Response
is success, I will receive an Array of countries in
Result
.

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

Observable<WebResponse<ArrayList<Country>>> countryListAsObservable = api.getCountryListAsObservable();
countryListAsObservable
.subscribeOn(AndroidSchedulers.mainThread())
.flatMap(
new Func1<WebResponse<ArrayList<Country>>, Observable<?>>() {
@Override
public Observable<Country> call(WebResponse<ArrayList<Country>> arrayListWebResponse) {

return Observable.from(arrayListWebResponse.getResult());
}
})
.map(new Func1<Country, String>() {
@Override
public String call(Country country) {
return country.getName();
}
})
.subscribe(
new Action1<String>() {
@Override
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
Response
. When this occurs I want to trigger the
Subscriber
s
onError()
.

How can I do that without breaking the chain?

Answer

Have you tried something like the code below?

countryListAsObservable.flatMap(new Func1<WebResponse<ArrayList<Country>>, Observable<?>>() {
    @Override
    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.