Last active
November 26, 2019 15:18
-
-
Save orwir/dd4114402747c6e9a2844f48b028c0bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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