Skip to content

Instantly share code, notes, and snippets.

@orwir
Last active November 26, 2019 15:18
Show Gist options
  • Save orwir/dd4114402747c6e9a2844f48b028c0bc to your computer and use it in GitHub Desktop.
Save orwir/dd4114402747c6e9a2844f48b028c0bc to your computer and use it in GitHub Desktop.
import android.arch.lifecycle.LiveData
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
class OnlineLiveData(context: Context) : LiveData<Boolean>() {
private val availableNetworks = mutableSetOf<Network>()
private val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private val request: NetworkRequest = NetworkRequest.Builder().build()
private val callback = object : ConnectivityManager.NetworkCallback() {
override fun onLost(network: Network) {
availableNetworks.remove(network)
update(availableNetworks.isNotEmpty())
}
override fun onAvailable(network: Network) {
availableNetworks.add(network)
update(availableNetworks.isNotEmpty())
}
}
override fun onActive() {
connectivityManager.registerNetworkCallback(request, callback)
}
override fun onInactive() {
connectivityManager.unregisterNetworkCallback(callback)
}
private fun update(online: Boolean) {
if (online != value) { // distinct
postValue(online)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment