How to get rid of Status.Unavailable in a callbackFlow?

48 views Asked by At

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?

1

There are 1 answers

2
Leviathan On BEST ANSWER

The ConnectivityManager takes some time to determine the current connection state, so the callbackFlow won't produce a value immediately. In your composable, however, the state object (retrieved by collectAsState) 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 the initial value to that function. That value will be taken until the flow produces its first value. You set that value to Staus.Unavailable (shouldn't it be Status instead of Staus?), so even when your device is connected, it is first displayed as Unavailable until the actual Available connectivity can be determined.

Just change the value for initial to whatever you want to be displayed until the connectivity status could be determined. It can be useful to define a new status Unknown or something similar to differentiate it from the other status values.