I\'d like to handle situations when there is no internet connection. Usually I\'d run:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemSer
With Retrofit 2, we use an OkHttp Interceptor implementation to check for network connectivity ahead of sending the request. If no network, throw an exception as appropriate.
This allows one to specifically handle network connectivity issues before hitting Retrofit.
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;
import io.reactivex.Observable
public class ConnectivityInterceptor implements Interceptor {
private boolean isNetworkActive;
public ConnectivityInterceptor(Observable isNetworkActive) {
isNetworkActive.subscribe(
_isNetworkActive -> this.isNetworkActive = _isNetworkActive,
_error -> Log.e("NetworkActive error " + _error.getMessage()));
}
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
if (!isNetworkActive) {
throw new NoConnectivityException();
}
else {
Response response = chain.proceed(chain.request());
return response;
}
}
}
public class NoConnectivityException extends IOException {
@Override
public String getMessage() {
return "No network available, please check your WiFi or Data connection";
}
}