Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@RequiresPermission(ACCESS_NETWORK_STATE)
fun ConnectivityManager.getNetworkConnectedFlow(): Flow<Boolean> = callbackFlow {
trySend(isConnected)
val networkStatusCallback = object : ConnectivityManager.NetworkCallback() {
override fun onUnavailable() {
trySend(false)
}
override fun onAvailable(network: Network) {
trySend(true)
}
override fun onLost(network: Network) {
trySend(false)
}
}
registerNetworkCallback(NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build(), networkStatusCallback)
awaitClose { unregisterNetworkCallback(networkStatusCallback) }
}.distinctUntilChanged()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment