Skip to content

Commit

Permalink
Merge pull request #196 from Infomaniak/fix-network-status
Browse files Browse the repository at this point in the history
fix: Sometimes no connection is received when multiple are available
  • Loading branch information
sirambd committed Jun 11, 2024
2 parents 5305aad + 267a85d commit 437ebb1
Showing 1 changed file with 7 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import android.os.Build
import android.util.Log
import androidx.lifecycle.LiveData
import io.sentry.Sentry
import java.net.UnknownHostException

class LiveDataNetworkStatus(context: Context) : LiveData<Boolean>() {

Expand All @@ -41,21 +40,19 @@ class LiveDataNetworkStatus(context: Context) : LiveData<Boolean>() {
private val networkStateObject = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
networks.remove(network)
postValue(!networks.all { !checkInternetConnectivity(it) })
postValue(hasAvailableNetwork())
}

override fun onAvailable(network: Network) {
networks.add(network)
postValue(checkInternetConnectivity(network))
postValue(hasAvailableNetwork())
}

fun checkInternetConnectivity(network: Network): Boolean {
return try {
network.getByName(ROOT_SERVER_CHECK_URL) != null
} catch (e: UnknownHostException) {
false
}
}
private fun hasAvailableNetwork() = networks.any(::hasInternetConnectivity)

fun hasInternetConnectivity(network: Network): Boolean = runCatching {
network.getByName(ROOT_SERVER_CHECK_URL) != null
}.getOrDefault(false)
}

override fun onActive() {
Expand Down

0 comments on commit 437ebb1

Please sign in to comment.