I have this code to check if internet connection is available or not.
public static boolean isOnline() {
Runtime runtime = Runtime.getRuntime();
try {
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
Now i want to do the same task using RxJava/RxAndroid. so how can I do that?
You can use ReactiveNetwork. This library do all work for checking connectivity state under hood and you can just observe connectivity state by subscribing to it.
You can check for Internet and listen for it's state using Rx-receivers
see : https://github.com/f2prateek/rx-receivers
If you're allowed to use the ConnectivityManager
this is a quick way to check for internet connection:
public static Observable<Boolean> isInternetOn(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return Observable.just(activeNetworkInfo != null && activeNetworkInfo.isConnected());
}
and then use it as follows:
private Observable<Object> executeNetworkCall() {
return isInternetOn(context)
.filter(connectionStatus -> connectionStatus)
.switchMap(connectionStatus -> doNetworkCall()));
}
If you need more info, this answer provides much more detailed instructions.
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