Detecting network change with ConnectivityManager & RxJava

Wonder how to check the network connectivity in Android? There is a new API that you can use but there aren’t many tutorials how to do it. Here is our simple way:

class NetworkControl @Inject constructor(context: Context) {

    private val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    private val tm = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager

    private val mobileNetworkOperator: String
        get() = "${tm.networkOperatorName} (${tm.networkOperator})"

    private val networkMonitorSubject = BehaviorSubject.create<State>()

    val stateObservable: Observable<State> =
        networkMonitorSubject
            .hide()
            .startWith(currentState)
            .distinctUntilChanged()
            .debounce(2, TimeUnit.SECONDS)

    val currentState: State
        get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            cm.getNetworkCapabilities(cm.activeNetwork)?.run {
                createNetworkState(hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR))
            } ?: createNetworkState()
        } else {
            cm.activeNetworkInfo?.run {
                createNetworkState(type == ConnectivityManager.TYPE_MOBILE)
            } ?: createNetworkState()
        }

    fun refreshNetworkState() {
        networkMonitorSubject.onNext(currentState)
    }

    private val isOnline: Boolean
        get() {
            val activeNetworkInfo = cm.activeNetworkInfo
            return activeNetworkInfo != null && activeNetworkInfo.isConnected
        }

    private fun createNetworkState(isCellular: Boolean = false): State = State(!isOnline, isCellular, mobileNetworkOperator)

    data class State(
        val isOffline: Boolean,
        val isMetered: Boolean,
        val mobileNetworkOperator: String
    ) {
        val isOnline: Boolean
            get() = !isOffline
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s