CMPConnectivityMonitor is a Compose Multiplatform library that provides seamless network connectivity monitoring for Android, iOS, wasmJs and Desktop platforms. It helps you easily detect and respond to changes in network status within your Compose Multiplatform applications.
- Monitors network connectivity status in real-time.
- Supports both Wi-Fi and Cellular network types.
- Provides connectivity status updates via a simple and consistent API.
- Supports iOS, Android, wasmJs and Desktop platforms.
Add the following dependency to your build.gradle.kts file:
commonMain.dependencies {
implementation("network.chaintech:compose-connectivity-monitor:1.0.2")
}In your AppActivity, initialize the ConnectivityMonitor:
class AppActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ConnectivityMonitor.initialize(this)
}
}Create an instance of ConnectivityMonitor in your shared code:
val connectivityMonitor = ConnectivityMonitor.instanceStart monitoring network connectivity:
connectivityMonitor.startMonitoring()Stop monitoring network connectivity when it is no longer needed:
connectivityMonitor.stopMonitoring()Perform a hard refresh to recheck the current network status:
connectivityMonitor.refresh()Use a StateFlow to observe the connectivity status:
val connectivityStatus: StateFlow<ConnectivityStatus> = connectivityMonitor.statusYou can then use this state in your Compose UI:
@Composable
fun ConnectivityStatusView() {
val status by connectivityMonitor.status.collectAsState()
when (status) {
ConnectivityStatus.CONNECTED,
ConnectivityStatus.CONNECTED_VIA_CELLULAR,
ConnectivityStatus.CONNECTED_VIA_WIFI -> {
// Show connected UI
}
ConnectivityStatus.NOT_CONNECTED,
ConnectivityStatus.CONNECTED_VIA_CELLULAR_WITHOUT_INTERNET,
ConnectivityStatus.CONNECTED_VIA_WIFI_WITHOUT_INTERNET -> {
// Show disconnected UI
}
ConnectivityStatus.DETERMINING -> {
// Show loading or determining UI
}
}
}The ConnectivityStatus enum provides various states to represent the connectivity status:
- CONNECTED
- CONNECTED_VIA_CELLULAR
- CONNECTED_VIA_CELLULAR_WITHOUT_INTERNET
- CONNECTED_VIA_WIFI
- CONNECTED_VIA_WIFI_WITHOUT_INTERNET
- DETERMINING
- NOT_CONNECTED
For an in-depth guide and detailed explanation, check out our comprehensive Medium Blog Post.
