Skip to content

Instantly share code, notes, and snippets.

@Eldhopj
Last active November 21, 2022 03:37
Show Gist options
  • Save Eldhopj/e167ad95adfc61f3247455698cce6ee5 to your computer and use it in GitHub Desktop.
Save Eldhopj/e167ad95adfc61f3247455698cce6ee5 to your computer and use it in GitHub Desktop.
Internet Connectivity observer
interface ConnectivityObserver {
fun observe(): Flow<Status>
enum class Status {
Available, Unavailable, Losing, Lost
}
}
@OptIn(ExperimentalCoroutinesApi::class)
class NetworkConnectivityObserver(
context: Context
) : ConnectivityObserver {
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
override fun observe(): Flow<ConnectivityObserver.Status> {
return callbackFlow {
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
super.onCapabilitiesChanged(network, networkCapabilities)
if (networkCapabilities.toString().contains("VALIDATED")) {
launch { send(ConnectivityObserver.Status.Available) }
} else {
launch { send(ConnectivityObserver.Status.Lost) }
}
}
override fun onAvailable(network: Network) {
super.onAvailable(network)
launch { send(ConnectivityObserver.Status.Available) }
}
override fun onLosing(network: Network, maxMsToLive: Int) {
super.onLosing(network, maxMsToLive)
launch { send(ConnectivityObserver.Status.Losing) }
}
override fun onLost(network: Network) {
super.onLost(network)
launch { send(ConnectivityObserver.Status.Lost) }
}
override fun onUnavailable() {
super.onUnavailable()
launch { send(ConnectivityObserver.Status.Unavailable) }
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(callback)
}
awaitClose { // when the coroutine scope destroyed
connectivityManager.unregisterNetworkCallback(callback)
}
}.distinctUntilChanged() // Prevent sending the same data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment