Skip to content

Instantly share code, notes, and snippets.

@KvRae
Created August 30, 2024 16:04
Show Gist options
  • Save KvRae/99f11d8f2be409a3fe41553d66ed6ef5 to your computer and use it in GitHub Desktop.
Save KvRae/99f11d8f2be409a3fe41553d66ed6ef5 to your computer and use it in GitHub Desktop.
Composable function that returns is network (wifi, mobile data) is available
/**
* A Composable function that provides network connectivity status.
*
* This function uses the `ConnectivityManager` to monitor changes in network connectivity.
* It returns a `Boolean` that indicates whether the network is currently available.
* The `Boolean` value will be updated automatically as the network connectivity status changes.
*
* This function is designed to be used within a Composable context and utilizes
* `remember` and `DisposableEffect` to manage the state and lifecycle of the network callback.
*
* Don't forget to add the necessary permissions to your `AndroidManifest.xml` file:
* ``` xml
* <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
* ```
*
*
* @param context The [Context] used to obtain the [ConnectivityManager].
* By default, it uses the current `LocalContext`.
*
* @return `true` if the network is available, `false` otherwise.
*/
@Composable
fun rememberNetworkConnectivity(
context: Context = LocalContext.current,
): Boolean {
val isNetworkAvailable = remember {
mutableStateOf(true)
}
val connectivityManager = context
.getSystemService(Context.CONNECTIVITY_SERVICE)
as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
isNetworkAvailable.value = true
}
override fun onLost(network: Network) {
isNetworkAvailable.value = false
}
}
DisposableEffect(Unit) {
connectivityManager.registerDefaultNetworkCallback(networkCallback)
onDispose {
connectivityManager.unregisterNetworkCallback(networkCallback)
}
}
return isNetworkAvailable.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment