0

I want to have application wide internet connection monitoring, for this purpose I'm using rxjava, I made a util class and got static method for connection state like this:

val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE)
            as ConnectivityManager
    val activeNetworkInfo = connectivityManager.activeNetworkInfo
    return Observable.just(activeNetworkInfo != null && activeNetworkInfo.isConnected)

after this in each activity I'm getting reference of this and subscribe on it like this:

isInternetOn(this).retry().subscribe({
        Toast.makeText(this@MainActivity, it.toString(), Toast.LENGTH_SHORT).show()
    })

the problem is when activity opens toast displays right status but when I turn off/turn on (change status of internet connection) nothing happens no toast appears

Thank you!

blackHawk
  • 6,047
  • 13
  • 57
  • 100

1 Answers1

1

Your solution will only give a one-time answer, for receiving updates for Network Change you should ReactiveNetwork.

ReactiveNetwork
  .observeNetworkConnectivity(context)
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(connectivity -> {
      if(connectivity.getState() == NetworkInfo.State.DISCONNECTED) {
          Log.d(TAG,"Connection lost");
        } else if(connectivity.getState() == NetworkInfo.State.CONNECTED) {
          Log.d(TAG,"Connected");
        }
  });
Yash Doshi
  • 111
  • 1
  • 2