-->

How to observe network changes in RxAndroid

2019-04-09 11:31发布

问题:

I’m using the code given here.

I put those code blocks as classes in my project’s util package. And then in the main activity class I wrote this..

class MenuActivity {

// Variable declaration
  private final CompositeSubscription mConnectionSubscription = new CompositeSubscription();

@Override
protected void onCreate(Bundle savedInstanceState) {

    // Some initialisation of UI elements done here

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

}

My goal is to monitor the changes and change a variable MyApp.isConnected defined in the MyApp class statically whenever the network changes to true false. Help would be appreciated. Thank you