The application network state observation
To use this library your minSdkVersion
must be >= 19
In your build.gradle :
dependencies {
implementation "com.mlsdev.connectivitylivedata:library:$latestVersion"
}
- 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"
})
}
}
- Sergey Petrosyuk, MLSDev
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!