Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to handle no network with Retrofit and RX-java

I want to check if the mobile is connected to internet before invoking my rx retrofit service. If not connected I want to return a fake Response that contains an error.

I ended with the solution below, using defer(), but I think it can be better, any hints ?

private Observable<Response> checkNetwork(Observable<Response> retrofitService) {
        return Observable.defer(new Func0<Observable<Response>>() {
            @Override
            public Observable<Response> call() {
                if (!isOnline()) {
                    return Observable.just(Response.error(R.string.error_no_network_label)));
                }
                return retrofitService;
            }
        });
    }
like image 886
tbruyelle Avatar asked Feb 25 '15 15:02

tbruyelle


People also ask

How do you use RxJava with retrofit?

RxAndroid is an extension of RxJava and it contains the Android threads to be used in the Android Environment. To use RxJava in retrofit environment we need to do just two major changes: Add the RxJava in Retrofit Builder. Use Observable type in the interface instead of Call.

What is the difference between RxJava and retrofit?

Rx gives you a very granular control over which threads will be used to perform work in various points within a stream. To point the contrast here already, basic call approach used in Retrofit is only scheduling work on its worker threads and forwarding the result back into the calling thread.

What is the purpose of a retrofit interface?

Retrofit is a REST Client for Java and Android allowing to retrieve and upload JSON (or other structured data) via a REST based You can configure which converters are used for the data serialization, example GSON for JSON.


1 Answers

You can implement retrofit ErrorHandler like described here: https://stackoverflow.com/a/21055979/2927901

And then handle thrown exception in doOnError method or your subscribers's onError method.

like image 76
VasyaFromRussia Avatar answered Sep 27 '22 20:09

VasyaFromRussia