Extract common code to update the Flow value

pull/716/head
Simon Marquis 2 years ago committed by GitHub
parent def5c4e881
commit 7819a0c6bc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -37,11 +37,18 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
) : NetworkMonitor { ) : NetworkMonitor {
override val isOnline: Flow<Boolean> = callbackFlow { override val isOnline: Flow<Boolean> = callbackFlow {
val connectivityManager = context.getSystemService<ConnectivityManager>() val connectivityManager = context.getSystemService<ConnectivityManager>()
?: run { if (connectivityManager == null) {
channel.trySend(false) channel.trySend(false)
channel.close() channel.close()
return@callbackFlow return@callbackFlow
} }
/**
* Sends the latest connectivity status to the underlying channel.
*/
fun update() {
channel.trySend(connectivityManager.isCurrentlyConnected())
}
/** /**
* The callback's methods are invoked on changes to *any* network, not just the active * The callback's methods are invoked on changes to *any* network, not just the active
@ -49,20 +56,14 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
* ConnectivityManager. * ConnectivityManager.
*/ */
val callback = object : NetworkCallback() { val callback = object : NetworkCallback() {
override fun onAvailable(network: Network) { override fun onAvailable(network: Network) = update()
channel.trySend(connectivityManager.isCurrentlyConnected())
}
override fun onLost(network: Network) { override fun onLost(network: Network) = update()
channel.trySend(connectivityManager.isCurrentlyConnected())
}
override fun onCapabilitiesChanged( override fun onCapabilitiesChanged(
network: Network, network: Network,
networkCapabilities: NetworkCapabilities, networkCapabilities: NetworkCapabilities,
) { ) = update()
channel.trySend(connectivityManager.isCurrentlyConnected())
}
} }
connectivityManager.registerNetworkCallback( connectivityManager.registerNetworkCallback(
@ -72,7 +73,7 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
callback, callback,
) )
channel.trySend(connectivityManager.isCurrentlyConnected()) update()
awaitClose { awaitClose {
connectivityManager.unregisterNetworkCallback(callback) connectivityManager.unregisterNetworkCallback(callback)

Loading…
Cancel
Save