Skip to content

Instantly share code, notes, and snippets.

@saqib-github-commits
Last active May 10, 2023 18:34
Show Gist options
  • Save saqib-github-commits/b4b0c59b0d4deb18c3c380753f2bb711 to your computer and use it in GitHub Desktop.
Save saqib-github-commits/b4b0c59b0d4deb18c3c380753f2bb711 to your computer and use it in GitHub Desktop.
interface NetworkConnectivityService {
val networkStatus: Flow<NetworkStatus>
}
class NetworkConnectivityServiceImpl @Inject constructor (
context: Context
): NetworkConnectivityService {
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
override val networkStatus: Flow<NetworkStatus> = callbackFlow {
val connectivityCallback = object : NetworkCallback() {
override fun onAvailable(network: Network) {
trySend(NetworkStatus.Connected)
}
override fun onUnavailable() {
trySend(NetworkStatus.Disconnected)
}
override fun onLost(network: Network) {
trySend(NetworkStatus.Disconnected)
}
}
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.build()
connectivityManager.registerNetworkCallback(request, connectivityCallback)
awaitClose {
connectivityManager.unregisterNetworkCallback(connectivityCallback)
}
}
.distinctUntilChanged()
.flowOn(Dispatchers.IO)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment