Skip to content

plusmobileapps/konnectivity

Repository files navigation

Konnectivity

A Kotlin multiplaform mobile library for checking the network connectivity status of a mobile device.

Supported Targets

  • Android
  • iOS - must use physical device to test, the iOS simulator does not work

Setup

buildscript {
    repositories {
        mavenCentral()
    }
}

Add Konnectivity to commonMain dependencies with the latest version.

Maven Central

kotlin {
    android()
    ios()

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("com.plusmobileapps:konnectivity:$version")
            }
        }
    }
}

Usage

Create a single instance of Konnectivity and inject into your app.

// create a single instance
val konnectivity: Konnectivity = Konnectivity()

Retrieve the current value of the network connectivity status.

val isConnected: Boolean = konnectivity.isConnected

val networkConnection: NetworkConnection = konnectivity.currentNetworkConnection
when (networkConnection) {
    NetworkConnection.NONE -> "Not connected to the internet"
    NetworkConnection.WIFI -> "Connected to wifi"
    NetworkConnection.CELLULAR -> "Connected to cellular"
}

Observe the latest value of the network connectivity status. Replace GlobalScope with your own CoroutineScope.

GlobalScope.launch {
    konnectivity.isConnectedState.collect { isConnected -> 
       // insert code
    }
}

GlobalScope.launch {
    konnectivity.currentNetworkConnectionState.collect { connection -> 
        when (connection) {
            NetworkConnection.NONE -> "Not connected to the internet"
            NetworkConnection.WIFI -> "Connected to wifi"
            NetworkConnection.CELLULAR -> "Connected to cellular"
        }
    }
}

Resources

About

KMM library for the current network connectivity status

Resources

License

Stars

Watchers

Forks

Packages

No packages published