|
|
|
@ -26,17 +26,25 @@ import android.net.NetworkRequest.Builder
|
|
|
|
|
import android.os.Build.VERSION
|
|
|
|
|
import android.os.Build.VERSION_CODES
|
|
|
|
|
import androidx.core.content.getSystemService
|
|
|
|
|
import androidx.tracing.Trace
|
|
|
|
|
import androidx.tracing.trace
|
|
|
|
|
import com.google.samples.apps.nowinandroid.core.network.Dispatcher
|
|
|
|
|
import com.google.samples.apps.nowinandroid.core.network.NiaDispatchers.IO
|
|
|
|
|
import dagger.hilt.android.qualifiers.ApplicationContext
|
|
|
|
|
import kotlinx.coroutines.CoroutineDispatcher
|
|
|
|
|
import kotlinx.coroutines.channels.awaitClose
|
|
|
|
|
import kotlinx.coroutines.flow.Flow
|
|
|
|
|
import kotlinx.coroutines.flow.callbackFlow
|
|
|
|
|
import kotlinx.coroutines.flow.conflate
|
|
|
|
|
import kotlinx.coroutines.flow.flowOn
|
|
|
|
|
import javax.inject.Inject
|
|
|
|
|
|
|
|
|
|
internal class ConnectivityManagerNetworkMonitor @Inject constructor(
|
|
|
|
|
@ApplicationContext private val context: Context,
|
|
|
|
|
@Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher,
|
|
|
|
|
) : NetworkMonitor {
|
|
|
|
|
override val isOnline: Flow<Boolean> = callbackFlow {
|
|
|
|
|
trace("NetworkMonitor.callbackFlow") {
|
|
|
|
|
val connectivityManager = context.getSystemService<ConnectivityManager>()
|
|
|
|
|
if (connectivityManager == null) {
|
|
|
|
|
channel.trySend(false)
|
|
|
|
@ -63,20 +71,26 @@ internal class ConnectivityManagerNetworkMonitor @Inject constructor(
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
trace("NetworkMonitor.registerNetworkCallback") {
|
|
|
|
|
val request = Builder()
|
|
|
|
|
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
|
|
|
|
|
.build()
|
|
|
|
|
connectivityManager.registerNetworkCallback(request, callback)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Sends the latest connectivity status to the underlying channel.
|
|
|
|
|
*/
|
|
|
|
|
channel.trySend(connectivityManager.isCurrentlyConnected())
|
|
|
|
|
|
|
|
|
|
Trace.endSection()
|
|
|
|
|
|
|
|
|
|
awaitClose {
|
|
|
|
|
connectivityManager.unregisterNetworkCallback(callback)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
.flowOn(ioDispatcher)
|
|
|
|
|
.conflate()
|
|
|
|
|
|
|
|
|
|
@Suppress("DEPRECATION")
|
|
|
|
|