[SB Refactor] Update the wifi network flow to use stateIn so that new

subscribers will receive the current value.

See linked bug for more details.

Fixes: 244173280
Test: manual: turn off wifi then look at icon in QS and lockscreen.
Verify QS and lockscreen show an updated wifi icon. (See video in bug)
Test: WifiRepositoryImplTest

Change-Id: I22910a15eb2e9755723e6e55c60357389273f8cf
This commit is contained in:
Caitlin Shkuratov
2022-08-29 16:31:14 +00:00
parent 0b136ce1ab
commit 78f2f2145a
2 changed files with 44 additions and 3 deletions

View File

@@ -46,7 +46,7 @@ import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
/**
* Provides data related to the wifi state.
@@ -118,12 +118,19 @@ class WifiRepositoryImpl @Inject constructor(
}
}
trySend(WIFI_NETWORK_DEFAULT)
connectivityManager.registerNetworkCallback(WIFI_NETWORK_CALLBACK_REQUEST, callback)
awaitClose { connectivityManager.unregisterNetworkCallback(callback) }
}
.shareIn(scope, started = SharingStarted.WhileSubscribed())
// There will be multiple wifi icons in different places that will frequently
// subscribe/unsubscribe to flows as the views attach/detach. Using [stateIn] ensures that
// new subscribes will get the latest value immediately upon subscription. Otherwise, the
// views could show stale data. See b/244173280.
.stateIn(
scope,
started = SharingStarted.WhileSubscribed(),
initialValue = WIFI_NETWORK_DEFAULT
)
override val wifiActivity: Flow<WifiActivityModel> =
if (wifiManager == null) {

View File

@@ -473,6 +473,40 @@ class WifiRepositoryImplTest : SysuiTestCase() {
job.cancel()
}
/** Regression test for b/244173280. */
@Test
fun wifiNetwork_multipleSubscribers_newSubscribersGetCurrentValue() = runBlocking(IMMEDIATE) {
var latest1: WifiNetworkModel? = null
val job1 = underTest
.wifiNetwork
.onEach { latest1 = it }
.launchIn(this)
getNetworkCallback()
.onCapabilitiesChanged(NETWORK, createWifiNetworkCapabilities(PRIMARY_WIFI_INFO))
assertThat(latest1 is WifiNetworkModel.Active).isTrue()
val latest1Active = latest1 as WifiNetworkModel.Active
assertThat(latest1Active.networkId).isEqualTo(NETWORK_ID)
assertThat(latest1Active.ssid).isEqualTo(SSID)
// WHEN we add a second subscriber after having already emitted a value
var latest2: WifiNetworkModel? = null
val job2 = underTest
.wifiNetwork
.onEach { latest2 = it }
.launchIn(this)
// THEN the second subscribe receives the already-emitted value
assertThat(latest2 is WifiNetworkModel.Active).isTrue()
val latest2Active = latest2 as WifiNetworkModel.Active
assertThat(latest2Active.networkId).isEqualTo(NETWORK_ID)
assertThat(latest2Active.ssid).isEqualTo(SSID)
job1.cancel()
job2.cancel()
}
@Test
fun wifiActivity_nullWifiManager_receivesDefault() = runBlocking(IMMEDIATE) {
underTest = WifiRepositoryImpl(