Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava/RxAndroid Check internet connection available or not

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?

like image 275
MSH Avatar asked Jan 22 '17 11:01

MSH


3 Answers

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.

like image 43
EgorD Avatar answered Sep 25 '22 09:09

EgorD


You can check for Internet and listen for it's state using Rx-receivers

see : https://github.com/f2prateek/rx-receivers

like image 21
Mohamed Yehia Avatar answered Sep 24 '22 09:09

Mohamed Yehia


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.

like image 126
Edson Menegatti Avatar answered Sep 25 '22 09:09

Edson Menegatti