Last active
November 21, 2022 03:37
-
-
Save Eldhopj/e167ad95adfc61f3247455698cce6ee5 to your computer and use it in GitHub Desktop.
Internet Connectivity observer
This file contains 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
interface ConnectivityObserver { | |
fun observe(): Flow<Status> | |
enum class Status { | |
Available, Unavailable, Losing, Lost | |
} | |
} |
This file contains 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
@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