Skip to content

Instantly share code, notes, and snippets.

@AdnanHabibMirza
Last active July 22, 2024 13:45
Show Gist options
  • Save AdnanHabibMirza/db24f94d5abbe90fe5c8695c61239ddb to your computer and use it in GitHub Desktop.
Save AdnanHabibMirza/db24f94d5abbe90fe5c8695c61239ddb to your computer and use it in GitHub Desktop.
Monitor network connectivity in android using callbackFlow.
interface NetworkMonitor {
val isOnline: Flow<Boolean>
}
class NetworkMonitorImpl @Inject constructor(
@ApplicationContext private val context: Context,
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
) : NetworkMonitor {
override val isOnline: Flow<Boolean>
get() = callbackFlow {
val connectivityManager = context.getSystemService<ConnectivityManager>()
if (connectivityManager == null) {
channel.trySend(false)
channel.close()
return@callbackFlow
}
val callback = object : NetworkCallback() {
private val networks = mutableSetOf<Network>()
override fun onAvailable(network: Network) {
networks += network
channel.trySend(true)
}
override fun onLost(network: Network) {
networks -= network
channel.trySend(networks.isNotEmpty())
}
}
val request = Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(request, callback)
channel.trySend(connectivityManager.isCurrentlyConnected())
awaitClose {
connectivityManager.unregisterNetworkCallback(callback)
}
}.flowOn(ioDispatcher).conflate()
@Suppress("DEPRECATION")
private fun ConnectivityManager.isCurrentlyConnected() = when {
VERSION.SDK_INT >= VERSION_CODES.M ->
activeNetwork
?.let(::getNetworkCapabilities)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
else -> activeNetworkInfo?.isConnected
} ?: false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment