Created
November 5, 2021 12:25
-
-
Save quanta-kt/906025a5c885fa2f3d3e77f463101791 to your computer and use it in GitHub Desktop.
Kotlin flow which observes internet connectivity on Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context | |
import android.net.ConnectivityManager | |
import android.net.Network | |
import android.net.NetworkCapabilities | |
import android.net.NetworkRequest | |
import android.util.Log | |
import androidx.core.content.getSystemService | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
import kotlinx.coroutines.channels.awaitClose | |
import kotlinx.coroutines.channels.onFailure | |
import kotlinx.coroutines.flow.Flow | |
import kotlinx.coroutines.flow.callbackFlow | |
/** | |
* Listens for network callbacks using connectivity manager and returns a flow | |
* which emits true when internet is available and false when not | |
* | |
* @param context the context | |
* @return A cold flow which emits boolean values indicating internet connectivity | |
*/ | |
@OptIn(ExperimentalCoroutinesApi::class) | |
fun connectivityStateFlow(context: Context): Flow<Boolean> = callbackFlow { | |
val connectivityManager: ConnectivityManager? = context.getSystemService() | |
val callbacks = object : ConnectivityManager.NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
super.onAvailable(network) | |
this@callbackFlow.trySend(true).onFailure { | |
Log.e("connectivityStateFlow", "Error while sending connectivity state to flow", it) | |
} | |
} | |
override fun onLost(network: Network) { | |
super.onLost(network) | |
this@callbackFlow.trySend(false).onFailure { | |
Log.e("connectivityStateFlow", "Error while sending connectivity state to flow", it) | |
} | |
} | |
} | |
val networkRequest = NetworkRequest.Builder() | |
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) | |
.build() | |
connectivityManager?.registerNetworkCallback(networkRequest, callbacks) | |
awaitClose { | |
connectivityManager?.unregisterNetworkCallback(callbacks) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment