Add flow support to NetworkConnectionManager

This commit is contained in:
Hinton 2024-10-24 11:18:56 -07:00
parent a325e92184
commit 5c62290a3d
No known key found for this signature in database
GPG key ID: 5F7295599C5D965C
2 changed files with 39 additions and 0 deletions

View file

@ -1,5 +1,7 @@
package com.x8bit.bitwarden.data.platform.manager package com.x8bit.bitwarden.data.platform.manager
import kotlinx.coroutines.flow.StateFlow
/** /**
* Manager to detect and handle changes to network connectivity. * Manager to detect and handle changes to network connectivity.
*/ */
@ -9,4 +11,6 @@ interface NetworkConnectionManager {
* available. * available.
*/ */
val isNetworkConnected: Boolean val isNetworkConnected: Boolean
val isNetworkConnectedFlow: StateFlow<Boolean>
} }

View file

@ -2,13 +2,21 @@ package com.x8bit.bitwarden.data.platform.manager
import android.content.Context import android.content.Context
import android.net.ConnectivityManager import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities import android.net.NetworkCapabilities
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.stateIn
/** /**
* Primary implementation of [NetworkConnectionManager]. * Primary implementation of [NetworkConnectionManager].
*/ */
class NetworkConnectionManagerImpl( class NetworkConnectionManagerImpl(
context: Context, context: Context,
private val externalScope: CoroutineScope
) : NetworkConnectionManager { ) : NetworkConnectionManager {
private val connectivityManager: ConnectivityManager = context private val connectivityManager: ConnectivityManager = context
.applicationContext .applicationContext
@ -19,4 +27,31 @@ class NetworkConnectionManagerImpl(
.getNetworkCapabilities(connectivityManager.activeNetwork) .getNetworkCapabilities(connectivityManager.activeNetwork)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
?: false ?: false
override val isNetworkConnectedFlow: StateFlow<Boolean>
get() = _connectedFlow
.stateIn(
scope = externalScope,
started = SharingStarted.WhileSubscribed(5000),
initialValue = isNetworkConnected
)
private val _connectedFlow = callbackFlow {
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network : Network) {
trySend(false)
}
override fun onCapabilitiesChanged(network : Network, networkCapabilities : NetworkCapabilities) {
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
&& networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
trySend(true)
}
}
}
connectivityManager.registerDefaultNetworkCallback(networkCallback)
awaitClose {
connectivityManager.unregisterNetworkCallback(networkCallback)
}
}
} }