expensivebelly
12/01/2021, 9:51 AMsuspend fun waitForNetworkConnection() = isConnectedFlow.filter { it }.single()
isConnectedFlow
is a StateFlow, initially false
(let’s assume we are in airplane mode in an Android app), then network connection is back, isConnectedFlow.value = true
, however, the waitForNetworkConnection
never ends and I don’t know why, I can see it only enters in the filter
once and the second emission is ignored? I’ve also tried
isConnectedFlow.first { it }
to no avail. Any help would be appreciatedbezrukov
12/01/2021, 10:45 AMfirst()
instead. So
isConnectedFlow.first { it }
should workexpensivebelly
12/01/2021, 10:52 AMprivate val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val _isConnectedFlow = MutableStateFlow(false)
suspend fun waitForNetworkConnection() = _isConnectedFlow.filter { it }.single()
private val callback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
_isConnectedFlow.value = true
}
override fun onLost(network: Network) {
_isConnectedFlow.value = false
}
override fun onLosing(
network: Network,
maxMsToLive: Int
) {
_isConnectedFlow.value = false
}
override fun onUnavailable() {
_isConnectedFlow.value = false
}
override fun onBlockedStatusChanged(
network: Network,
blocked: Boolean
) {
_isConnectedFlow.value = !blocked
}
}
callback
,meaning, one is a suspend
function and we have the callback
emitting and the waitForNetworkConnection
is unable to see the changes…suspend fun waitForNetworkConnection() {
while (true) {
val value = _isConnectedFlow.value
if (value) break
delay(100)
}
}
still does not work, _isConnectedFlow.value is always false, regardless of whether the callback
has called _isConnectedFlow.value = true