-
-
Notifications
You must be signed in to change notification settings - Fork 6
Open
Labels
fixA bug fix for the user, not a fix to a build script.A bug fix for the user, not a fix to a build script.
Description
Right now we just let the API call proceed and populate the error from Retrofit.
It can end up with delays and piling up multiple error messages as it retrys.
There are multiple approaches to tackle this at the UI level or the ViewModel level.
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
fun isNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = connectivityManager.activeNetwork ?: return false
val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
return capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}
OR
class ConnectivityObserver(context: Context) {
private val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkAvailable: LiveData<Boolean> = MutableLiveData()
init {
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
(networkAvailable as MutableLiveData).postValue(true)
}
override fun onLost(network: Network) {
(networkAvailable as MutableLiveData).postValue(false)
}
}
connectivityManager.registerDefaultNetworkCallback(networkCallback)
}
}
Then in the viewmodel
class MyViewModel(application: Application) : AndroidViewModel(application) {
private val connectivityObserver = ConnectivityObserver(application)
val isNetworkAvailable = connectivityObserver.networkAvailable
fun fetchData() {
if (isNetworkAvailable.value == true) {
// Proceed with Retrofit call
} else {
// Handle lack of internet connectivity
}
}
}
Metadata
Metadata
Assignees
Labels
fixA bug fix for the user, not a fix to a build script.A bug fix for the user, not a fix to a build script.