Quick question: ```suspend fun waitForNetworkConne...
# flow
e
Quick question:
Copy code
suspend 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
Copy code
isConnectedFlow.first { it }
to no avail. Any help would be appreciated
b
single() waits for flow completion to ensure it's single value. You need to use
first()
instead. So
Copy code
isConnectedFlow.first { it }
should work
e
no, it doesn’t
Copy code
private 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
    }
  }
that’s the whole chunk of code, I’m starting to think it’s the
callback
,meaning, one is a
suspend
function and we have the
callback
emitting and the
waitForNetworkConnection
is unable to see the changes…
Because even if I do this hack:
Copy code
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
never mind, it was a Dagger problem