I am implementing offline mode for my application, my plan is to put the local db between the UI and API Requests.
I have this fragment and his viewmodel with this init block:
init {
viewModelScope.launch(Dispatchers.IO) {
// context required here
loadVehicles()
}
}
Now, inside loadVehicles, I want to check if I am online or not, if I am, I will simply make a call to the API to update my local database in case there is anything new.
fun isOnline(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (connectivityManager != null) {
val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
if (capabilities != null) {
return true
}
}
return false
}
This was the simplest code I could find to test if I am online or not, and this function needs the context, which is unaccessable from the init block of the view model.
Looking forward hearing other suggestions of doing things if there is something I can improve with mine.