Christian Dräger
05/27/2021, 6:25 AMandroid.os.NetworkOnMainThreadException
i already figured out this is because i just call an http client (which is blocking) in the main activity (main/ui thread) as you can see on the screenshot.
what do i need to do to make my http call with my client of choice work?
stackoverflow was saying something about AsyncTasks but the answers has been very old and looked pretty different from my jetpack compose code 😄
I found solutions like: https://stackoverflow.com/a/13136668/10562333 that would just deactivate the restriction but that feels wrong to me.
From what I understood so far I would need to do the call in a background thread instead of the main thread. Can I do this by wrapping my call in a coroutine and if so how? What would be the state of the art way to tackle this problem? (bearbeitet)felislynx
05/27/2021, 6:26 AMfelislynx
05/27/2021, 6:26 AMfelislynx
05/27/2021, 6:26 AMfelislynx
05/27/2021, 6:27 AMChristian Dräger
05/27/2021, 6:29 AMfelislynx
05/27/2021, 6:31 AMfelislynx
05/27/2021, 6:31 AMfelislynx
05/27/2021, 6:33 AMfelislynx
05/27/2021, 6:33 AMfelislynx
05/27/2021, 6:33 AMChristian Dräger
05/27/2021, 6:44 AMfelislynx
05/27/2021, 6:49 AMfelislynx
05/27/2021, 6:51 AMclass API(){
private val client = HttpClient() {
install(JsonFeature) {
serializer = KotlinxSerializer()
}
install(HttpTimeout) {
requestTimeoutMillis = 30000
}
}
fun checkIfInternetAvailable() = GlobalScope.async {
try {
val response = client.get<HttpResponse> {
url("<https://www.google.com>")
timeout {
// timeout config
requestTimeoutMillis = 2000
}
}
response.status.value in 200..299
} catch (e: Exception) {
false
}
}
}
felislynx
05/27/2021, 6:51 AMZun
05/27/2021, 1:17 PM<https://www.gstatic.com/generate_204>
.
2. You don't really need to do this. You can also perform an API call to your API and depending on the callback there decide if you want to show a "no internet" dialog
3. What if the user can't connect to Google (Google is blocked in some countries) but can connect to your API. Why would you want to refuse the user access? @felislynxfelislynx
05/27/2021, 1:19 PMZach Klippenstein (he/him) [MOD]
05/27/2021, 3:39 PMMutableStateFlow
or LiveData
. Typically you don’t store or expose the network response directly, but some higher-level data derived from it. Eventually, that’s what your composable consumes, e.g. via collectAsState
or observeAsState
, and those *asState
functions will make sure your composable updates when the data from your higher layers change.