|
|
|
@ -30,13 +30,17 @@ import kotlinx.coroutines.channels.awaitClose
|
|
|
|
|
import kotlinx.coroutines.flow.Flow
|
|
|
|
|
import kotlinx.coroutines.flow.callbackFlow
|
|
|
|
|
import kotlinx.coroutines.flow.conflate
|
|
|
|
|
import Kotlinx.coroutines.flow.flowOf
|
|
|
|
|
import javax.inject.Inject
|
|
|
|
|
|
|
|
|
|
class ConnectivityManagerNetworkMonitor @Inject constructor(
|
|
|
|
|
@ApplicationContext private val context: Context,
|
|
|
|
|
) : NetworkMonitor {
|
|
|
|
|
override val isOnline: Flow<Boolean> = callbackFlow {
|
|
|
|
|
override val isOnline: Flow<Boolean> {
|
|
|
|
|
val connectivityManager = context.getSystemService<ConnectivityManager>()
|
|
|
|
|
?: return flowOf(false)
|
|
|
|
|
|
|
|
|
|
return callbackFlow {
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* The callback's methods are invoked on changes to *any* network, not just the active
|
|
|
|
@ -60,7 +64,7 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
connectivityManager?.registerNetworkCallback(
|
|
|
|
|
connectivityManager.registerNetworkCallback(
|
|
|
|
|
Builder()
|
|
|
|
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
|
|
|
.build(),
|
|
|
|
@ -70,21 +74,17 @@ class ConnectivityManagerNetworkMonitor @Inject constructor(
|
|
|
|
|
channel.trySend(connectivityManager.isCurrentlyConnected())
|
|
|
|
|
|
|
|
|
|
awaitClose {
|
|
|
|
|
connectivityManager?.unregisterNetworkCallback(callback)
|
|
|
|
|
connectivityManager.unregisterNetworkCallback(callback)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
.conflate()
|
|
|
|
|
|
|
|
|
|
@Suppress("DEPRECATION")
|
|
|
|
|
private fun ConnectivityManager?.isCurrentlyConnected() = when (this) {
|
|
|
|
|
null -> false
|
|
|
|
|
else -> when {
|
|
|
|
|
private fun ConnectivityManager.isCurrentlyConnected() = when {
|
|
|
|
|
VERSION.SDK_INT >= VERSION_CODES.M ->
|
|
|
|
|
activeNetwork
|
|
|
|
|
?.let(::getNetworkCapabilities)
|
|
|
|
|
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
|
|
|
?: false
|
|
|
|
|
else -> activeNetworkInfo?.isConnected ?: false
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else -> activeNetworkInfo?.isConnected
|
|
|
|
|
} ?: false
|
|
|
|
|
}
|
|
|
|
|