Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SamueldaCostaAraujoNunes/6f61cb1e7b5f191bfb41b7804dc72066 to your computer and use it in GitHub Desktop.
Save SamueldaCostaAraujoNunes/6f61cb1e7b5f191bfb41b7804dc72066 to your computer and use it in GitHub Desktop.
@RequiresApi(Build.VERSION_CODES.N)
class NetworkConnectivityObserver @Inject constructor(
context: Context
) {
enum class Status {
AVAILABLE, UNAVAILABLE, LOSING, LOST;
fun hasConnection(): Boolean = this == AVAILABLE || this == LOSING
}
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
fun observe(): Flow<Status> {
return callbackFlow {
val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
launch { send(Status.AVAILABLE) }
}
override fun onLosing(network: Network, maxMsToLive: Int) {
super.onLosing(network, maxMsToLive)
launch { send(Status.LOSING) }
}
override fun onLost(network: Network) {
super.onLost(network)
launch { send(Status.LOST) }
}
override fun onUnavailable() {
super.onUnavailable()
launch { send(Status.UNAVAILABLE) }
}
}
connectivityManager.registerDefaultNetworkCallback(callback)
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}.distinctUntilChanged()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment