I have this code to get internet connection status:
override fun getStatus() = callbackFlow {
val callbackFlow = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
trySend(Status.Available)
}
override fun onLost(network: Network) {
trySend(Staus.Lost)
}
override fun onUnavailable() {
trySend(Status.Unavailable)
}
}
manager.registerDefaultNetworkCallback(callbackFlow)
awaitClose {
manager.unregisterNetworkCallback(callbackFlow)
}
}.distinctUntilChanged()
I call din function from the ViewModel class:
fun getStatus() = repo.getStatus()
And inside the activity I have:
val status = viewModel.getStatus().collectAsState(
initial = Status.Unavailable
).value
Text(
text = "$status"
)
The problem is when I start the app, when I'm connected, for a short period of time I get Unavailable and right after that Available. How to get rid of Unavailable?
The ConnectivityManager takes some time to determine the current connection state, so the
callbackFlowwon't produce a value immediately. In your composable, however, the state object (retrieved bycollectAsState) needs a value right away, even when the flow hasn't had enough time yet to produce a value. That's why you have to provide theinitialvalue to that function. That value will be taken until the flow produces its first value. You set that value toStaus.Unavailable(shouldn't it beStatusinstead ofStaus?), so even when your device is connected, it is first displayed asUnavailableuntil the actualAvailableconnectivity can be determined.Just change the value for
initialto whatever you want to be displayed until the connectivity status could be determined. It can be useful to define a new statusUnknownor something similar to differentiate it from the other status values.