Skip to content

Latest commit

 

History

History
69 lines (51 loc) · 2.6 KB

README.md

File metadata and controls

69 lines (51 loc) · 2.6 KB

License Download

ConnectivityLiveData

The application network state observation

Setup

To use this library your minSdkVersion must be >= 19

In your build.gradle :

dependencies {
    implementation "com.mlsdev.connectivitylivedata:library:$latestVersion"
}

Usage

  • Add ConnectivityLiveData into your ViewModel
  class MainViewModel(application: Application) : AndroidViewModel(application), LifecycleObserver {

      private val connectivityLiveData = ConnectivityLiveData(application)

      fun getConnectivity(): LiveData<ConnectivityState> =
          Transformations.switchMap(connectivityLiveData) { connectivityState ->
              MutableLiveData<ConnectivityState>().apply { value = connectivityState }
          }
  }
  • Observe the connectivity state in your Activity or Fragment
  class MainActivity : AppCompatActivity(), LifecycleOwner {

      lateinit var connectivityText: TextView
      lateinit var viewModel: MainViewModel

      override fun onCreate(savedInstanceState: Bundle?) {
          super.onCreate(savedInstanceState)
          setContentView(R.layout.activity_main)

          connectivityText = findViewById(R.id.text_connectivity_state)
          viewModel = MainViewModel(application)

          viewModel.getConnectivity().observe(this, Observer { connectivityState ->
              connectivityText.text = if (connectivityState == ConnectivityState.CONNECTED)
                  "Your app is able to perform network operations"
              else
                  "Your app isn't able to fetch date from the network"
          })

      }
  }

Authors

About MLSDev

MLSDev.com

ConnectivityLiveData is maintained by MLSDev, Inc. We specialize in providing all-in-one solution in mobile and web development. Our team follows Lean principles and works according to agile methodologies to deliver the best results reducing the budget for development and its timeline.

Find out more here and don't hesitate to contact us!