Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Created Aug 17, 2021
Embed
What would you like to do?
/**
* 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