Create a class that notifies observe classes about the network connection and disconnection.
/**
* Internet Util class to observer connection.
*/
class InternetConnectionUtil constructor(context: Context, listener: (Int) -> Unit) {
init {
val connectivityManager = context.getSystemService(CommonActivity.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkRequest = NetworkRequest.Builder().build()
connectivityManager.registerNetworkCallback(networkRequest, object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
listener(1)
}
override fun onLost(network: Network) {
super.onLost(network)
listener(0)
}
})
}
}
After that create a ViewModel
which would observe the InternetConnectionUtil
class LiveVideoViewModel: ViewModel() {
private val _internetStateFlow = MutableStateFlow(-1)
val internetStateFlow = _internetStateFlow.asStateFlow()
fun monitorInternetConnection(context: Context) {
InternetConnectionUtil(context) {
_internetStateFlow.value = it
}
}
}
Then it's time to observe it either in Activity
or Fragment
depend on your use case
lifecycleScope.launch {
viewModel.internetStateFlow.collect {
if (it == 1) {
//internet connected
Log.d("network_connection:", "internet connect= $playerFragment")
} else {
//internet lost
Log.d("network_connection:", "internet disconnect= $playerFragment")
}
}
}
Thank you for reading the article