Skip to content

Instantly share code, notes, and snippets.

@mahdi-malv
Last active November 10, 2018 08:13
Show Gist options
  • Save mahdi-malv/c236e6ff0b0eb9e7f2098d0c9f79f4b6 to your computer and use it in GitHub Desktop.
Save mahdi-malv/c236e6ff0b0eb9e7f2098d0c9f79f4b6 to your computer and use it in GitHub Desktop.
A function (Using RxJava) to check network availability and be notifed when it's status changes.
//Check network with RxJava2
@SuppressLint("MissingPermission") // AccessNetworkState -> Add it yourself
fun isInternetOn(context: Context): Observable<Boolean> {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo: NetworkInfo?
activeNetworkInfo = connectivityManager.activeNetworkInfo
return Observable.just(activeNetworkInfo != null && activeNetworkInfo.isConnected)
.map { it }
.distinctUntilChanged()
}
// Simply subscribe the function in order to use.
// If network CHANGES you will be notified!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment