Check active network for connectivity state each time network changes

Change-Id: I5d3eb0251f62a57a5767911167067d35aeec8e6a
pull/445/head
Adetunji Dahunsi 2 years ago
parent c62673d035
commit 841f58ef26

@ -35,18 +35,30 @@ import kotlinx.coroutines.flow.conflate
class ConnectivityManagerNetworkMonitor @Inject constructor(
@ApplicationContext private val context: Context
) : NetworkMonitor {
override val isOnline: Flow<Boolean> = callbackFlow<Boolean> {
override val isOnline: Flow<Boolean> = callbackFlow {
val connectivityManager = context.getSystemService<ConnectivityManager>()
/*
The callback's methods are invoked on changes to *any* network, not just the active
network. So to check for network connectivity, one must query the active network of the
ConnectivityManager.
*/
val callback = object : NetworkCallback() {
override fun onAvailable(network: Network) {
channel.trySend(true)
channel.trySend(connectivityManager.isCurrentlyConnected())
}
override fun onLost(network: Network) {
channel.trySend(false)
channel.trySend(connectivityManager.isCurrentlyConnected())
}
}
val connectivityManager = context.getSystemService<ConnectivityManager>()
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
channel.trySend(connectivityManager.isCurrentlyConnected())
}
}
connectivityManager?.registerNetworkCallback(
Builder()

Loading…
Cancel
Save