Created
September 8, 2022 15:37
-
-
Save SamueldaCostaAraujoNunes/6f61cb1e7b5f191bfb41b7804dc72066 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
@RequiresApi(Build.VERSION_CODES.N) | |
class NetworkConnectivityObserver @Inject constructor( | |
context: Context | |
) { | |
enum class Status { | |
AVAILABLE, UNAVAILABLE, LOSING, LOST; | |
fun hasConnection(): Boolean = this == AVAILABLE || this == LOSING | |
} | |
private val connectivityManager = | |
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) | |
fun observe(): Flow<Status> { | |
return callbackFlow { | |
val callback = object : ConnectivityManager.NetworkCallback() { | |
override fun onAvailable(network: Network) { | |
super.onAvailable(network) | |
launch { send(Status.AVAILABLE) } | |
} | |
override fun onLosing(network: Network, maxMsToLive: Int) { | |
super.onLosing(network, maxMsToLive) | |
launch { send(Status.LOSING) } | |
} | |
override fun onLost(network: Network) { | |
super.onLost(network) | |
launch { send(Status.LOST) } | |
} | |
override fun onUnavailable() { | |
super.onUnavailable() | |
launch { send(Status.UNAVAILABLE) } | |
} | |
} | |
connectivityManager.registerDefaultNetworkCallback(callback) | |
awaitClose { | |
connectivityManager.unregisterNetworkCallback(callback) | |
} | |
}.distinctUntilChanged() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment