Hi all, I’m trying to find a way to create a self-...
# android
f
Hi all, I’m trying to find a way to create a self-updating ObservableBoolean for the device’s network status. There’s a lot of talk about using a
<http://android.net|android.net>.conn.CONNECTIVITY_CHANGE
intent, however that’s been deprecated. Anyone got any good ideas on how to implement this on devices running Android N or over?
s
Copy code
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val request = NetworkRequest.Builder().build()
val isConnected: Flow<Boolean> = callbackFlow {
    val callback = object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {
            offer(true)
        }
        override fun onLost(network: Network) {
            offer(false)
        }
    }
    cm.registerNetworkCallback(request, callback)
    awaitClose {
        cm.unregisterNetworkCallback(callback) 
    }
}
👍 2