-
-
Save PatilShreyas/605d2f69419f72c97cb89a2a819c51bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Network Utility to observe availability or unavailability of Internet connection | |
*/ | |
@ExperimentalCoroutinesApi | |
fun Context.observeConnectivityAsFlow() = callbackFlow { | |
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
val callback = NetworkCallback { connectionState -> trySend(connectionState) } | |
val networkRequest = NetworkRequest.Builder() | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) | |
.build() | |
connectivityManager.registerNetworkCallback(networkRequest, callback) | |
// Set current state | |
val currentState = getCurrentConnectivityState(connectivityManager) | |
trySend(currentState) | |
// Remove callback when not used | |
awaitClose { | |
// Remove listeners | |
connectivityManager.unregisterNetworkCallback(callback) | |
} | |
} | |
fun NetworkCallback(callback: (ConnectionState) -> Unit): ConnectivityManager.NetworkCallback { | |
return object : ConnectivityManager.NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
callback(ConnectionState.Available) | |
} | |
override fun onLost(network: Network) { | |
callback(ConnectionState.Unavailable) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment