Created
December 18, 2019 12:44
-
-
Save robertlevonyan/2a1931a5f9f45a6079bcd120957a2f2e to your computer and use it in GitHub Desktop.
Network Listener Flow
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
@ExperimentalCoroutinesApi | |
fun notifyNetwork() = channelFlow<Boolean> { | |
val networkRequest = NetworkRequest.Builder() | |
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) | |
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) | |
.build() | |
val connectivityManager: ConnectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
connectivityManager.registerNetworkCallback(networkRequest, object : ConnectivityManager.NetworkCallback() { | |
override fun onLost(network: Network) { | |
super.onLost(network) | |
launch { | |
channel.offer(false) | |
} | |
} | |
override fun onAvailable(network: Network) { | |
super.onAvailable(network) | |
launch { | |
channel.offer(true) | |
} | |
} | |
}) | |
awaitClose { | |
println("Network closed") | |
} | |
} |
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
fun main() { | |
CoroutineScope(Dispatchers.Main).launch { | |
notifyNetwork().collect { | |
println(if (it) "Network connected" else "No Internet") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment