-
-
Save saqib-github-commits/b4b0c59b0d4deb18c3c380753f2bb711 to your computer and use it in GitHub Desktop.
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 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