NetworkUtils
interface NetworkUtils
Utility for monitoring network connectivity state changes.
This interface provides reactive access to network connectivity status using Android's ConnectivityManager. It enables real-time monitoring of network availability, allowing the application to respond to connectivity changes (e.g., showing offline UI, pausing network operations, or retrying failed requests).
Usage Example
In a ViewModel, observe network state to update UI accordingly:
@HiltViewModel
class MyViewModel @Inject constructor(
private val networkUtils: NetworkUtils
) : ViewModel() {
val networkState = networkUtils.getCurrentState()
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), NetworkState.UNAVAILABLE)
val isOnline = networkState.map { it == NetworkState.CONNECTED }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)
}Content copied to clipboard
In a Repository, check network state before making requests:
class MyRepository @Inject constructor(
private val networkUtils: NetworkUtils,
private val networkDataSource: NetworkDataSource
) {
suspend fun syncData(): Result<Unit> = suspendRunCatching {
networkUtils.getCurrentState().first().let { state ->
if (state != NetworkState.CONNECTED) {
throw IOException("No network connection")
}
}
networkDataSource.fetchData()
}
}Content copied to clipboard
See also
for possible connectivity states