From 7819a0c6bcf0e2d9cb073f2978aed9b52df85ff2 Mon Sep 17 00:00:00 2001 From: Simon Marquis Date: Mon, 8 May 2023 12:50:01 +0200 Subject: [PATCH] Extract common code to update the Flow value --- .../util/ConnectivityManagerNetworkMonitor.kt | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/ConnectivityManagerNetworkMonitor.kt b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/ConnectivityManagerNetworkMonitor.kt index 4c68946c8..4b8f049c0 100644 --- a/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/ConnectivityManagerNetworkMonitor.kt +++ b/core/data/src/main/java/com/google/samples/apps/nowinandroid/core/data/util/ConnectivityManagerNetworkMonitor.kt @@ -37,11 +37,18 @@ class ConnectivityManagerNetworkMonitor @Inject constructor( ) : NetworkMonitor { override val isOnline: Flow = callbackFlow { val connectivityManager = context.getSystemService() - ?: run { - channel.trySend(false) - channel.close() - return@callbackFlow - } + if (connectivityManager == null) { + channel.trySend(false) + channel.close() + return@callbackFlow + } + + /** + * Sends the latest connectivity status to the underlying channel. + */ + fun update() { + channel.trySend(connectivityManager.isCurrentlyConnected()) + } /** * The callback's methods are invoked on changes to *any* network, not just the active @@ -49,20 +56,14 @@ class ConnectivityManagerNetworkMonitor @Inject constructor( * ConnectivityManager. */ val callback = object : NetworkCallback() { - override fun onAvailable(network: Network) { - channel.trySend(connectivityManager.isCurrentlyConnected()) - } + override fun onAvailable(network: Network) = update() - override fun onLost(network: Network) { - channel.trySend(connectivityManager.isCurrentlyConnected()) - } + override fun onLost(network: Network) = update() override fun onCapabilitiesChanged( network: Network, networkCapabilities: NetworkCapabilities, - ) { - channel.trySend(connectivityManager.isCurrentlyConnected()) - } + ) = update() } connectivityManager.registerNetworkCallback( @@ -72,7 +73,7 @@ class ConnectivityManagerNetworkMonitor @Inject constructor( callback, ) - channel.trySend(connectivityManager.isCurrentlyConnected()) + update() awaitClose { connectivityManager.unregisterNetworkCallback(callback)