5

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?

MSH
  • 147
  • 4
  • 10
  • Possible duplicate of [Internet check, where to place when using MVP, RX and Retrofit](http://stackoverflow.com/questions/38242462/internet-check-where-to-place-when-using-mvp-rx-and-retrofit) – Edson Menegatti Jan 22 '17 at 12:01

5 Answers5

7

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.

Community
  • 1
  • 1
Edson Menegatti
  • 4,006
  • 2
  • 25
  • 40
  • If someone wants a continuous pinging you would do something like: (i.e every 2 seconds)just use `Observable .interval(0, 2, TimeUnit.SECONDS).scheduleOn(Schedulers.io()).flatMap { isInternetOn(this) } ` – Lamour Dec 10 '18 at 20:53
3

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.

EgorD
  • 886
  • 6
  • 12
1

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

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

Mohamed Yehia
  • 400
  • 1
  • 5
  • 15
0
public class MainActivity extends AppCompatActivity{
  private Subscription sendStateSubscription;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      final Observable<RxNetwork.State> sendStateStream =
              RxNetwork.stream(this);

      sendStateSubscription = AppObservable.bindActivity(
            this, sendStateStream
      ).subscribe(new Action1<RxNetwork.State>() {
          @Override public void call(RxNetwork.State state) {
              if(state == RxNetwork.State.NOT_CONNECTED)
                  Timber.i("Connection lost");
              else
                  Timber.i("Connected");
          }
      });
  }

  @Override protected void onDestroy() {
      sendStateSubscription.unsubscribe();
      sendStateSubscription = null;

      super.onDestroy();
  }
}
Lino
  • 5,084
  • 3
  • 21
  • 39
-3

//ping any website with the following code to check for internet connection

public boolean isConnected() throws InterruptedException, IOException
{
    String command = "ping -c 1 google.com";
    return (Runtime.getRuntime().exec (command).waitFor() == 0);
}