A Kotlin multiplaform mobile library for checking the network connectivity status of a mobile device.
- Android
- iOS - must use physical device to test, the iOS simulator does not work
buildscript {
repositories {
mavenCentral()
}
}Add Konnectivity to commonMain dependencies with the latest version.
kotlin {
android()
ios()
sourceSets {
val commonMain by getting {
dependencies {
implementation("com.plusmobileapps:konnectivity:$version")
}
}
}
}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"
}
}
}