How to observe network changes in RxAndroid

六眼飞鱼酱① 提交于 2019-12-06 04:18:36

问题


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 😄


回答1:


Try to use rxnetwork-android:

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();
    }
}



回答2:


You asked me for an answer in another thread. I'm answering late, because I needed some time to develop and test solution, which I find good enough.

I've recently created new project called ReactiveNetwork.

It's open-source and available at: https://github.com/pwittchen/ReactiveNetwork.

You can add the following dependency to your build.gradle file:

dependencies {
  compile 'com.github.pwittchen:reactivenetwork:x.y.z'
}

Then, you can replace x.y.z with the latest version number.

After that, you can use library in the following way:

 ReactiveNetwork.observeNetworkConnectivity(context)        
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Action1<ConnectivityStatus>() {
      @Override public void call(Connectivity connectivity) {
        if(connectivity.getState() == NetworkInfo.State.DISCONNECTED) {
          Timber.i("Connection lost");
        } else if(connectivity.getState() == NetworkInfo.State.CONNECTED) {
          Timber.i("Connected");
        }
      }
    });

You can also use filter(...) method from RxJava if you want to react only on a single type of event.

You can create a subscription in onResume() method and then unsubscribe it in onPause() method inside Activity.

You can find more examples of usage and sample app on the website of the project on GitHub.

Moreover, you can read about NetworkInfo.State enum from Android API, which is now used by the library.



来源:https://stackoverflow.com/questions/31098430/how-to-observe-network-changes-in-rxandroid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!